【问题标题】:ASP .Net Gridview bind to data only when clicking updateASP .Net Gridview 仅在单击更新时绑定到数据
【发布时间】:2009-11-05 19:32:46
【问题描述】:

这是我希望控件工作的方式。在 gridview 中的一行上单击编辑。其中一列中有一个文本框,即使数据库中有该列的数据,我也希望它为空白,但是当我单击更新时,我希望用户输入的任何新文本都可以更新该列的数据库。这将是单向数据绑定,但另一种方式?

【问题讨论】:

    标签: asp.net data-binding gridview


    【解决方案1】:

    以下是我使用 sql 数据源并生成 select、update 和 delete 方法的方法。

    首先,您需要将要编辑的任何列设置为带有项目模板和编辑项目模板的模板字段:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="ID" DataSourceID="SqlDataSource1" 
            onrowupdating="GridView1_RowUpdating">
        <Columns>
        <asp:TemplateField HeaderText="City" SortExpression="City">
            <ItemTemplate>
               <asp:Label runat="server" Text='<%# Eval("City") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
               <asp:TextBox runat="server"  ID="txtCityEdit" Text=""></asp:TextBox>
            </EditItemTemplate>
         </asp:TemplateField>
         </Columns>
    </asp:GridView>
    

    接下来处理gridview的更新事件:

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //find the value control who's value you want
            TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCityEdit");
    
            //since we are not using a bound column for city we need to explicitly insert the value
            //into the update parameter.
            SqlDataSource1.UpdateParameters["City"].DefaultValue = tb.Text;
        }
    

    即使您使用的不是 SQL 数据源,这也应该是基本解决方案。

    【讨论】:

    • 这并不完全适合我,但绝对让我走上了正轨!我最大的问题是从模板字段中获取文本框的值,因为智能感知不会给我。我尝试像您的示例一样使用 UpdateParameters,但出现空引用错误,然后我尝试将我的新参数添加到集合中,但这也不起作用。我最终将我的新值添加到“NewValues”集合中并且它起作用了。
    【解决方案2】:
    // Find notes textbox
    TextBox tb = (TextBox)MyActiveReferrals.Rows[e.RowIndex].FindControl("NotesTextBox");
    e.NewValues.Add("Notes", tb.Text);
    

    我使用了 linq 数据源。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多