网格中的索引值中的行始终从零开始。如何正确获取行索引值

时间:2014-03-24 08:41:59

标签: c# asp.net

每当执行grid时,行id的值都为0,因此deleteedit操作效果不佳。

任何人请帮助我。提前致谢

protected void Grd_View_RowCommand(Object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
    if (e.CommandName == "Edit")
    {
        int rowid = 1;
         rowid = Convert.ToInt32(e.CommandArgument);
        Session["rowid"]= rowid;
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection(myStr);
        SqlCommand cmd = new SqlCommand("Select * from CustomerProfMain where CustomerCode='" +rowid+ "'", con);
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        con.Open();
        DataSet ds = new DataSet();
        sda.Fill(ds);
        dt=ds.Tables[0];
        TextBox1.Text = dt.Rows[0]["CustomerName"].ToString();
        TextBox2.Text=dt.Rows[0]["Address"].ToString();
        TextBox3.Text=dt.Rows[0]["TellNo"].ToString();
        TextBox4.Text=dt.Rows[0]["FaxNo"].ToString();
        TextBox5.Text=dt.Rows[0]["Email"].ToString();
        Button1.Text = "Update";
    }
    if (e.CommandName == "Delete")
    {
        int rowid = Convert.ToInt32(e.CommandArgument);
        Session["rowid"] = rowid;
        // DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection(myStr);
        SqlCommand cmd = new SqlCommand("Delete from CustomerProfMain where CustomerCode='"+rowid+"' ", con);
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        //DataSet ds = new DataSet();
        //sda.Fill(ds);
        //dt = ds.Tables[0];
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用CommandSource属性。请尝试

GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer; 
int rowIndex    = gvr.RowIndex;

您将获得问题中的行索引

 int index = Convert.ToInt32(e.CommandArgument);

如果您使用的是<asp:CommandField ShowEditButton="True" /><asp:ButtonField ButtonType="Button" Text="Save" CommandName="Edit" />

但最好的方法是使用CommandArgument来设置aspx:

CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' 

然后你会得到如下的RowIndex:

int RowIndex = int.Parse(e.CommandArgument.ToString()); 

请参阅here或  here了解CommandArgument

中的Gridview