2011-06-22 22 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