I add all row CheckBox
in my Gridview
helping with this article
.
Here is my Calculate Button
code;
protected void Calculate开发者_如何学JAVA_Click(object sender, EventArgs e)
{
bool atLeastOneRowDeleted = false;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("ProductSelector");
if (cb != null && cb.Checked)
{
atLeastOneRowDeleted = true;
int productID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
Response.Write(string.Format( "This would have deleted ProductID {0}<br />", productID));
}
}
}
But when i do that, getting strange error like this;
How can i solve this problem?
Best Regards, Soner
Make sure you have DataKeys defined in your GridView definition
<asp:gridview id="GridView2"
datakeynames="productID"
...
...>
enter code here
</asp:gridview>
Also try adding a check for DataRow like this
foreach (GridViewRow row in GridView1.Rows)
{
if(row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)row.FindControl("ProductSelector");
if (cb != null && cb.Checked)
{
atLeastOneRowDeleted = true;
int productID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
Response.Write(string.Format( "This would have deleted ProductID {0}<br />", productID));
}
}
}
It could be related to the way youre populating your gridview, or the way youre setting your GridView to store the DataKeys, could you post both codes, where you set up your GridView component on your .aspx page (the html code) and where you populate it?
EDIT:
I have tried your example, and the only diferrence is that I aquire a datasource from a List intead of a DataSource control, is running perfectly here, and I Ctrl+c/Ctrl+v your code, so take a look;
public class MyClass { public int productId { get; set; } public string MUS_K_ISIM { get; set; } }
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<MyClass> ChechkBoxDataSource = new List<MyClass>();
ChechkBoxDataSource.Add(new MyClass() { productId = 1, MUS_K_ISIM = "Stack" });
ChechkBoxDataSource.Add(new MyClass() { productId = 2, MUS_K_ISIM = "Overflow" });
ChechkBoxDataSource.Add(new MyClass() { productId = 3, MUS_K_ISIM = "Example" });
GridView1.DataSource = ChechkBoxDataSource;
GridView1.DataBind();
}
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)row.FindControl("ProductSelector");
if (cb != null && cb.Checked)
{
int productID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
Response.Write(string.Format("This would have deleted ProductID {0}<br />", productID));
}
}
}
}
精彩评论