我有一个带有文本框的gridview
我想在按钮上获取此文本框的值
,但我总是收到" 0"(默认)值
我认为这个问题与ViewState有关,但我不确定
请告诉我我做错了什么?
源代码:
protected void Page_Load(object sender, EventArgs e)
{
DataSet dataSet = new DataSet("MyDataSet");
DataTable table = new DataTable();
table.Columns.Add(new DataColumn("NameValue"));
table.Columns.Add(new DataColumn("Number"));
table.Columns.Add(new DataColumn("NumberValue"));
dataSet.Tables.Add(table);
DataRow row = dataSet.Tables[0].NewRow();
row[0] = "Name";
row[1] = "0";
dataSet.Tables[0].Rows.Add(row);
this.MyGridView.DataSource = dataSet;
this.MyGridView.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox txtsn = ((TextBox)this.MyGridView.Rows[0].FindControl("NumberTextBox"));
string sn = txtsn.Text;
}
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:GridView ID="MyGridView" AutoGenerateColumns="false" ShowHeader="false" runat="server" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="NameLabel" runat="server" Text='<%#Eval("NameValue")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="NumberTextBox" runat="server" Text='<%#Eval("NumberValue")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
问题在于,即使在寄回后,您始终将网格绑定到其DataSource
。这覆盖了用户所做的所有更改。
而是使用IsPostBack
属性:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
DataSet dataSet = new DataSet("MyDataSet");
DataTable table = new DataTable();
table.Columns.Add(new DataColumn("NameValue"));
table.Columns.Add(new DataColumn("Number"));
table.Columns.Add(new DataColumn("NumberValue"));
dataSet.Tables.Add(table);
DataRow row = dataSet.Tables[0].NewRow();
row[0] = "Name";
row[1] = "0";
dataSet.Tables[0].Rows.Add(row);
this.MyGridView.DataSource = dataSet;
this.MyGridView.DataBind();
}
}
只有在更改某些内容时才需要重新加载DataSource
(F.E.删除或添加了记录,用户单击了排序列或您的分页)。但是,您只能在适当的事件处理程序中而不是在page_load中执行此操作。因此,最好将此代码包裹在可以从任何地方调用的方法。
您的数据将您的网格绑定在寄回上,这引起了此问题。您想检查请求是否是帖子:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback)
{
DataSet dataSet = new DataSet("MyDataSet");
DataTable table = new DataTable();
table.Columns.Add(new DataColumn("NameValue"));
table.Columns.Add(new DataColumn("Number"));
table.Columns.Add(new DataColumn("NumberValue"));
dataSet.Tables.Add(table);
DataRow row = dataSet.Tables[0].NewRow();
row[0] = "Name";
row[1] = "0";
dataSet.Tables[0].Rows.Add(row);
this.MyGridView.DataSource = dataSet;
this.MyGridView.DataBind();
}
}