【发布时间】:2015-09-19 08:16:24
【问题描述】:
有一个文本框可以从 Gridview 中搜索值。当值显示然后每次我单击编辑时,它都会转到 Gridview 的第一个索引行。我只想编辑已按 ID 搜索的行。 例如,如果我搜索第 8 行中的值。它显示第 8 行,这很好,但是当我单击编辑时,它再次转到第一行。为什么会这样?
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
protected void BindGridView()
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from tblInventory", con);
con.Open();
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("select * from tblInventory where (Part like '%" + txtSearch.Text + "%') or (Brand like '%" + txtSearch.Text + "%' )", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
TextBox Part = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPart");
TextBox Description = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDescription");
TextBox Qty = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtQty");
DropDownList Brand = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlBrand");
TextBox ItemType = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtItemType");
SqlCommand cmd = new SqlCommand("update tblInventory set Part='" + Part.Text + "',Description='" + Description.Text + "',Qty='" + Qty.Text + "',Brand='" + Brand.Text + "',ItemType='" + ItemType.Text + "' where ID=" + id, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
【问题讨论】:
-
你能提供更多关于搜索的细节吗?当您搜索时,gridview 是否过滤并显示具有您在 textBox 中键入的值的行?你有截图吗?
-
@R.C - 我认为它与此类似:例如,如果我搜索第 8 行中的值。它显示第 8 行,这很好,但是当我单击编辑时,它再次转到第一行。为什么会这样? stackoverflow.com/questions/25128461/…
-
现在我可以说的是,在 Page_Load 中使用 !IsPostback 条件绑定您的网格视图数据。大多数情况下,这是丢失编辑索引的原因
-
我认为按钮搜索有问题。请检查详细信息。我将如何只修复这部分?
-
基本上,当您搜索一个值时,例如说搜索到的值,它最初可能位于任何行(8、4、100...)中的任何位置,它是一种过滤然后这个值显示在第 1 行或第 2 行等中...然后它基本上是您选择的第 1 行或第 2 行。例如,不是实际行 = 第 8 行。所以尝试使用 gridview 的 EnablePersistedSelection 属性。可能这可能会有所帮助。 msdn.microsoft.com/en-us/library/…
标签: c# asp.net gridview datagridview edit