我在CheckBox
帮助article
中添加了所有行Gridview
。
这是我的Calculate Button
代码;
protected void Calculate_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));
}
}
}
但是当我这样做时,会发生这样的奇怪错误;
我该如何解决这个问题?
最诚挚的问候,Soner
答案 0 :(得分:4)
确保在GridView定义中定义了DataKeys
<asp:gridview id="GridView2"
datakeynames="productID"
...
...>
enter code here
</asp:gridview>
还可以尝试像这样添加DataRow检查
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));
}
}
}
答案 1 :(得分:2)
它可能与您填充gridview的方式有关,或者您设置GridView存储DataKeys的方式,您是否可以发布两个代码,在.aspx页面上设置GridView组件(html代码)你填充它的地方?
编辑:
我试过你的例子,唯一不同的是我从DataSource控件的List intead中获取数据源,在这里运行得很好,我按Ctrl + c / Ctrl + v你的代码,所以看一看;
公共类MyClass { public int productId {get;组; } public string MUS_K_ISIM {get;组; } }
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));
}
}
}
}