TextBox in GridView not holding its value on postback

六月ゝ 毕业季﹏ 提交于 2019-12-11 07:45:27

问题


I have a gridview on a .NET forms application, and on postback, I am not seeing the values entered in the textbox within a gridview.

ASPX:

<asp:GridView ID="gvItems" runat="server" AutoGenerateColumns="false" ShowHeader="false" DataKeyNames="ItemId" EnableViewState="true">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:TextBox ID="txtItem" runat="server" Text="0" EnableViewState="true" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="ItemId" /> 
     </Columns>
</asp:GridView>

<asp:Button runat="server" ID="btn" Text="Submit" OnClick="btn_OnClick" OnClientClick="javascript:return someClientStuff();" />

Code Behind:

protected void btn_OnClick(object sender, System.EventArgs e)
{
    foreach(GridViewRow row in gvItems.Rows)
    {                
        if (row.RowType == DataControlRowType.DataRow)
        {
            var itemId = Convert.ToInt32(gvItems.DataKeys[row.RowIndex].Values[0]);
            var itemValue = ((row.Cells[0].FindControl("txtItem") as TextBox).Text;
        }
}

I am seeing itemId populated for each row, but itemValue is always empty string.

Been a while since I worked on a forms application, any help is appreciated!


回答1:


I will assume that the DataBind of the GridView is not in if(!IsPostBack). Add this to the Page_Load

if(!IsPostBack)
{
    gvItems.DataSource = soruceOftheGrid
    gvItems.DataBind();
}



回答2:


On the button click, try to store the values in the view state and within page load event, try to assign the viewstate back to the grid view as for each postback, page load event is called. Its good to assign the values back to grid view within page load, this will help you to retain the values you have entered.



来源:https://stackoverflow.com/questions/26538330/textbox-in-gridview-not-holding-its-value-on-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!