每当执行grid时,行id的值都为0
,因此delete
和edit
操作效果不佳。
任何人请帮助我。提前致谢
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];
}
}
答案 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