C# 选中gridview列复选框
我正在用C开发一个应用程序,其中我使用的是datagridview,gridview的第一列包含复选框,我想检查复选框是否为真,但它给了我一个例外:“对象引用未设置为对象的实例”。代码如下C# 选中gridview列复选框,c#,asp.net,C#,Asp.net,我正在用C开发一个应用程序,其中我使用的是datagridview,gridview的第一列包含复选框,我想检查复选框是否为真,但它给了我一个例外:“对象引用未设置为对象的实例”。代码如下 private void btnDelete_Click(object sender, EventArgs e) { StudentDAL s = new StudentDAL(); try {
private void btnDelete_Click(object sender, EventArgs e)
{
StudentDAL s = new StudentDAL();
try
{
for (int i = 0; i < this.dataGridView1.RowCount; i++)
{
if (!DBNull.Value.Equals(this.dataGridView1.Rows[i].Cells[0]) && (bool)this.dataGridView1.Rows[i].Cells[0].Value == true)
{
s.delete(Convert.ToInt32(this.dataGridView1.Rows[i].Cells[1].Value));
i--;
}
}
this.dataGridView1.DataSource = s.getAll();
}
catch (Exception nn)
{
}
}
请帮助我。您试图引用一个尚未初始化的对象。我相信此实例行[I]
尝试在for循环中放置一个断点,并逐步执行F10,检查抛出异常时我所处的位置。您试图引用的对象尚未初始化,我相信在该实例行[i]中 尝试在for循环中放置一个断点,并逐步执行F10,检查抛出异常时我所处的位置。添加更多验证
foreach (DataGridViewRow rw in this.dataGridView1.Rows)
{
if (rw.Cells.Count > 2 &&
rw.Cells[0].Value != DBNull.Value && String.IsNullOrWhiteSpace(rw.Cells[0].Value.ToString()) &&
((bool)rw.Cells[0].Value) &&
rw.Cells[1].Value != DBNull.Value && String.IsNullOrWhiteSpace(rw.Cells[1].Value.ToString()))
{
s.delete(Convert.ToInt32(rw.Cells[1].Value));
}
}
添加更多验证
foreach (DataGridViewRow rw in this.dataGridView1.Rows)
{
if (rw.Cells.Count > 2 &&
rw.Cells[0].Value != DBNull.Value && String.IsNullOrWhiteSpace(rw.Cells[0].Value.ToString()) &&
((bool)rw.Cells[0].Value) &&
rw.Cells[1].Value != DBNull.Value && String.IsNullOrWhiteSpace(rw.Cells[1].Value.ToString()))
{
s.delete(Convert.ToInt32(rw.Cells[1].Value));
}
}
首先,您必须找到您的复选框控件,然后您可以检查它是否已选中,如下所示:
Int32 i;
CheckBox k;
for (i = 0; i < GridView1.Rows.Count; i++)
{
k = ((CheckBox)(GridView1.Rows[i].Cells[0].FindControl("chk")));
if (k.Checked == true)
{
//your code here
}
else
{
//your code here
}
}
首先,您必须找到您的复选框控件,然后您可以检查它是否已选中,如下所示:
Int32 i;
CheckBox k;
for (i = 0; i < GridView1.Rows.Count; i++)
{
k = ((CheckBox)(GridView1.Rows[i].Cells[0].FindControl("chk")));
if (k.Checked == true)
{
//your code here
}
else
{
//your code here
}
}
您应该首先通过FindControl方法获取复选框控件,然后检查它是否选中。您应该首先通过FindControl方法获取复选框控件,然后检查它是否选中。在它第一次检查条件时,它抛出异常。您可以发布堆栈跟踪吗?在它第一次检查条件时,它抛出异常例外您可以发布堆栈跟踪吗?