我用gridview的控件来显示数据,在我对里面的一行数据删除的时候无法获得该行的主键值,不知是什么原因,报错是什么index范围错误,请大家给指点一下,谢谢!急用!
 SqlConnection con = new SqlConnection("Data Source=ZZF;Initial Catalog=GreenWell;User ID=sa;Password=admin");
        string selstr = "select * from News";
        con.Open();
        SqlDataAdapter sda = new SqlDataAdapter(selstr,con);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        
        this.GridView1.DataSource = ds.Tables[0].DefaultView;
        this.GridView1.DataBind();
        con.Close();
protected void  GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
  string aa = this.GridView1.DataKeys[e.RowIndex].Values[0].ToString();
        
        string str = "DELETE FROM News where NewsID="+aa;
}<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="800px" ShowHeader="False" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing">
            <Columns>
                <asp:BoundField DataField="NewsID" Visible="False" />
                 
                <asp:TemplateField>
                    <ItemStyle Width="50px" />
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemStyle Width="150px" />
                    <ItemTemplate>
                        <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("picture")%>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Title" HeaderText="新闻标题" />
                <asp:CommandField HeaderText="编辑" ShowEditButton="True">
                    <ItemStyle Width="80px" />
                </asp:CommandField>
                <asp:CommandField HeaderText="删除" ShowDeleteButton="True">
                    <ItemStyle Width="80px" />
                </asp:CommandField>
            </Columns>
        </asp:GridView>

解决方案 »

  1.   

    this.GridView1.DataSource = ds.Tables[0].DefaultView; 
    this.GridView1.DataKeyNames = new string[] { "aaa"};
    this.GridView1.DataBind();
     
     
      

  2.   

    GridView没有DataKeyNames
    你的 string aa = this.GridView1.DataKeys[e.RowIndex].Values[0].ToString(); 当然会报错了
      

  3.   

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="800px" ShowHeader="False" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" DataKeyNames="NewsID"
      

  4.   

     两个问题:
    1、this.GridView1.DataKeyNames = new string[] { "aaa"};指定key
    2、写错了吧LZ
    protected void  GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 

      string aa = this.GridView1.DataKeys[e.RowIndex].Values[0].ToString(); --------
            
            string str = "DELETE FROM News where NewsID="+aa; 

    应该:GridView2.DataKeys[e.RowIndex].Value.ToString()