C# Linq to datagrid 具有更新功能

标签 c# linq datagrid

我想做一个允许用户编辑当前信息以及添加新内容的数据网格。我还需要它有一个我可以响应的复选框。基本上它将是一个名称和一个 isActive 字段,该字段由数据网格每一行中的复选框表示。

我想为此使用 linq,但不确定是否可行。这是一个 ASP.Net 网站。

如果有人有任何反馈,那就太好了。

最佳答案

做起来很容易。

GridView 有许多事件可用于某些操作(删除、编辑、取消和更新)。例如,OnRowUpdating 和 OnRowEditing 看起来像这样:

<asp:GridView ID="gvTest" runat="Server" OnRowUpdating="gvTest_RowUpdating" OnRowEditing="gvTest_RowEditing">
    <Columns>
    <asp:TemplateField>
        <ItemTemplate>
        <asp:Button ID="btnUpdate" runat="Server" Text="Update" CommandName="Update">
        <asp:Button ID="btnEdit" runat="Server" Text="Edit" CommandName="Edit">
        </ItemTemplate>
    </asp:TemplateField>
    </Columns>
</asp:GridView>

然后在代码隐藏中实现更新(编辑、删除等)的事件处理程序。为了让自己的生活更轻松,您可以切换到设计 View ,找到您的 GridView 并调出事件(看起来像闪电的图标),然后双击一个事件,它的 stub 将自动为您创建在代码隐藏中,html 标记也会自动创建。 RowUpdating 事件处理程序的示例如下所示:

protected void gvTest_RowUpdating(object sender, GridViewUpdateEventArgs e) {
  // Convenient access to the row index that was selected
  int theRowIndex = e.RowIndex;
  GridViewRow gvr = gvTest.Rows[e.RowIndex];

  // Now its just a matter of tracking down your various controls in the row and doing 
  // whatever you need to with them
  TextBox someTxtBox = (TextBox)gvr.FindControl("theTextBoxID");
  DropDownList someDDL = (DropDownList)gvr.FindControl("theDDL_ID");

  // Perhaps some business class that you have setup to take the value of the textbox
  // and insert it into a table
  MyDoSomethingClass foo = new MyDoSomethingClass {
    FirstName = someTxtBox.Text,
    Age = someDDL.SelectedItem.Value
  };

  foo.InsertPerson();
}

请注意,您也可以使用 OnRowCommand 而不是使用更新(编辑、删除等)事件,但 OnRowCommand 没有可供您随时使用的选定行索引。如果你想要它,那么你必须在你的标记中做一些魔术。

<asp:Button ID="btnDoSomething" runat="Server" Text="Do Something" CommandArgument="<%# Container.DataItemIndex %>" CommandName="DoSomething">

然后在 RowCommand 事件中,您执行类似这样的操作以获取行索引:

protected void gvTest_RowCommand(object sender, GridViewCommandEventArgs e) {
  int rowIdx = Convert.ToInt32(e.CommandArgument);
}

编辑:

实际上,访问您的 GridView 绑定(bind)到的键非常简单。假设你的 GridView 只绑定(bind)了一个键,你可以通过这种方式获取键(假设我们在 RowCommand 事件中):

int rowIdx = Convert.ToInt32(e.CommandArgument);
int someKeyID = Convert.ToInt32(gvTest.DataKeys[rowIdx].Value);

关于C# Linq to datagrid 具有更新功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6442186/

相关文章:

c# - 如何链接和应用外部 css 文件

c# - 未创建注册表项

c# - 验证器控件必须始终显示 ="Dynamic"

c# - 如何将 LINQ 查询附加到彼此?

c# - LINQ 查询 : Determining if object in one list exists in another based on key

c# - 如何跟踪DataGrid WPF MVVM的更改

c# - 将 Canvas 保存为 png C# wpf

c# - 创建新动态对象时的内联操作

c# - 填充动态 DataGrid 时,BackgroundWorker 无法防止 ProgressBar 卡住

c# - 单击 ASP.NET DataGrid 的 EditCommandColumn 中的更新不会启动代码隐藏中定义的 Click 事件