gpt4 book ai didi

C# Linq to datagrid 具有更新功能

转载 作者:太空宇宙 更新时间:2023-11-03 16:44:35 24 4
gpt4 key购买 nike

我想做一个允许用户编辑当前信息以及添加新内容的数据网格。我还需要它有一个我可以响应的复选框。基本上它将是一个名称和一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com