我正在使用gridview。当我单击编辑按钮时,会出现更新和取消按钮。 在修改来自EditItemTemplate的文本框中的值时,新值不会显示在事件处理程序rowupdating()中,而是获取在呈现页面时显示的值。如何从这些文本框中获取新值并继续进行? 这是代码。
<asp:GridView ID="GridView1" runat="server" AutoGenerateEditButton="true" AutoGenerateColumns="false"
AutoGenerateDeleteButton="true" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtId" runat="server" Text='<%# Eval("id") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("cpuname") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("cpuname") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text='<%# Eval("status") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtStatus" runat="server" Text='<%# Eval("status") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox text = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
}
答案 0 :(得分:5)
你应该在这里使用双向绑定。即绑定而不是Eval:
<asp:TextBox ID="txtId" runat="server" Text='<%# Bind("id") %>'></asp:TextBox>
以下是文档链接:
Data-Binding Expressions Overview
这是我背后的代码:
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Data");
for(int i = 0; i < 20; i++)
table.Rows.Add(new object[] { i });
GridView1.DataSource = table;
if(!IsPostBack) // <<<<<<<<<<<<
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox text = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtId");
}
答案 1 :(得分:1)
如果您已编写代码以在页面加载中绑定网格,请确保它包含在if(!IsPostBack)
中
我希望它有所帮助
答案 2 :(得分:0)
试试这个
TextBox text = (TextBox)GridView1.Rows[e.EditIndex].FindControl("txtName");
答案 3 :(得分:0)
这最终为我工作。
protected void MyGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string value = e.NewValues[0].ToString();
// ...
}
答案 4 :(得分:-1)
我跟随柏拉图和它的工作!
将if(!IsPostBack)
放在databind()
之前,
并在GridView1.DataBind();
GridView1.EditIndex = e.NewEditIndex;
之后插入GridView1_RowEditing