[英]Asp.net grid view template fields data persist
我有一個網格視圖,其中包含4個模板字段,每個模板字段包含一個文本框。
現在,我已將這些模板字段與數據源綁定在一起。 當我作為用戶在文本框中輸入一些數據並單擊“保存”按鈕(該按鈕不是gridview的一部分,而是Webform中的單個按鈕)時,我無法在click事件處理程序中獲取值在文件后面的代碼中。 請幫我。
ASPX檔案
<asp:TemplateField HeaderText="col1">
<ControlStyle Height="25px" Width="60px" />
<ItemTemplate>
<asp:TextBox ID="txt1" runat="server" Text='<%# Bind("[col1]") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="col2">
<ControlStyle Height="25px" Width="60px" />
<ItemTemplate>
<asp:TextBox ID="txt2" runat="server" Text='<%# Bind("[col2]") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="col3">
<ControlStyle Height="25px" Width="60px" />
<ItemTemplate>
<asp:TextBox ID="txt3" runat="server" Text='<%# Bind("[col3]") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="col4">
<ControlStyle Height="25px" Width="60px" />
<ItemTemplate>
<asp:TextBox ID="txt4" runat="server" Text='<%# Bind("[col4]") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
文件后面的代碼
protected void ButtonAdd_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvEdit.Rows)
{
string a = ((TextBox)row.FindControl("col1")).Text;
//above line gives a null value
}
}
您需要遍歷GridViewRowCollection
,然后對於每一行,通過標記中提供的Id
查找控件。 例如:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvEdit.Rows)
{
var txt1 = row.FindControl("txt1") as TextBox;
var txt2 = row.FindControl("txt2") as TextBox;
var txt3 = row.FindControl("txt3") as TextBox;
var txt4 = row.FindControl("txt4") as TextBox;
// access the Text property of each, e.g. txt1.Text
}
}
更新:確保在進行數據源綁定時,它僅在初始加載時發生,而不會在隨后的回發中發生,否則您的更改將每次都被重置。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = // data source
GridView1.DataBind();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.