2012-04-20 109 views
3

我正在使用C#ASP.net,並且對它有新意,並且需要在下面完成。ASP.net Gridview Itemtemplate下拉列表

在我的VS2010 Web應用程序項目中,我有webformGridview,它從表中提取數據。

在網格中,我有Commandfiled Button(column1)和Item template with Dropdownlist(column2)。

用例是,用戶首先從3個列表項(H,L和M)中選擇一個listitem,然後選擇命令按鈕。

我不能夠提前從選定的行弄清楚如何提取選擇listitem

protected void GridView2_SelectedIndexChanged(object sender, EventArgs e) 
{ 

    GridViewRow row = GridView2.SelectedRow; 
    Label4.Text = "You selected " + row.Cells[4].Text + "."; 
    Label5.Text = "You selected this list item from dropdownlist " + ???? ; 
} 

感謝。

回答

2

GridViewRow對象提供方法FindControl(與所有容器控件一樣)通過其id訪問行中的控件。例如,如果你的DropDownListMyDropDown一個id,你可以使用下面的方法訪問它的設定值:

GridViewRow row = GridView2.SelectedRow; 
DropDownList MyDropDown = row.FindControl("MyDropDown") as DropDownList; 
string theValue = MyDropDown.SelectedValue; 
// now do something with theValue 

這是訪問您的GridView所有控件的推薦方法。您希望避免像row.Cells[#]這樣的事情儘可能避免,因爲當您重新安排或添加/刪除GridView中的列時,它很容易中斷。

+0

謝謝您的解決方案,並提示避免細胞指數 – user219628 2012-04-20 02:24:45