gridview的删除事件,测试时发生错误,protected void Button1_Click(object sender, EventArgs e)
    {        SqlConnection conn = new SqlConnection(str);//str数据库连接串 
        SqlDataAdapter ad = new SqlDataAdapter("select * from a  ", conn);        DataSet ds = new DataSet();
        conn.Open();        ad.Fill(ds);//填充数据集        GridView1.DataSource = ds;
        GridView1.DataKeyNames = new string[] { "TopicID" };
        GridView1.DataBind();
        conn.Close();        
        for(int j=0;j<GridView1.Rows.Count;j++)
        {
            CheckBox cb2 = new CheckBox();
            cb2 = (CheckBox)GridView1.Rows[j].FindControl("checkbox1");
             if (cb2.Checked == true)
             {
                 string strg = "delete from a where TopicID='" + GridView1.DataKeys[j].Value + "'";
                 SqlCommand cmd = new SqlCommand(strg, conn);
                 conn.Open();
                 int Row = cmd.ExecuteNonQuery();
                 if (Row > 0)
                 {
                     Response.Write("<Script >alert(\"删除成功!\")</Script>");
                 }
                 conn.Close();
             }
        }
    }

解决方案 »

  1.   

    GridView1.DataKeys[j].Values[0]试试这样
      

  2.   

    恩 是啊 有对象为Null 一般提示这样的错误就应该想到这点
      

  3.   

    可能是cb2 = (CheckBox)GridView1.Rows[j].FindControl("checkbox1"); 出错了,
    提示cb2为null
      

  4.   

    你说的是这句?
     SqlConnection conn = new SqlConnection(str);//str数据库连接串 
    应该不是吧,我测试的时候直接写数据库连接的啊,
    是不是别的地方出错了,
      

  5.   

    这个说实话,楼主你只有自己调试一下,找到为null的变量。