2011-06-22 21 views
2

我想做一个数据网格,允许用户编辑当前信息以及添加新的东西。我也需要它有一个我可以回复的复选框。基本上它将是一个名称,并且是一个isActive字段,由datagrid的每一行中的复选框表示。C#Linq到具有更新功能的数据网格

我想用linq来做这个,但我不确定它是否可能。这是一个ASP.Net网站。

如果有人有任何反馈,这将是真棒。

回答

0

容易做到。

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> 

然后实现在您的代码隐藏更新(编辑,删除等)的事件处理程序。为了让自己的生活更轻松,您可以切换到设计视图,找到您的GridView并调出事件(看起来像闪电般的图标),然后双击一个事件,它的存根将自动为您创建在代码隐藏中,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); 
} 

编辑:

访问密钥(S)是你的GridView是其实很简单。假设您的GridView控件绑定到一个键,就可以得到这样的键(假设我们在RowCommand事件):

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

我得到“GridViewUpdateEventArgs不包含rowIndex的定义' –

+0

感谢您花时间回复此问题。你说我可以找到控件,我只需通过模板添加控件?我需要显示一个名称和一个isActive字段,这就是它。我希望他们能够编辑东西并删除它。 –

+0

@Blake - 我不确定为什么RowIndex属性不适用于您。自从GridView推出ASP.NET 2.0以来,它一直是EventArgs的一个属性。你在哪个框架上? – Jagd