2012-04-20 16 views
7

我正在研究一個Asp.NET項目,並試圖用文本屬性設置下拉列表的選定值。例如,我有一個文本test下拉列表中的項目。以編程方式,我可以通過Text?將其設置爲selecteditem。我正在使用follwing代碼,但無法正常工作。如何使用DropDownList.text來選擇

protected void Page_Load(object sender, EventArgs e) 
{ 
    string t = "test"; 
    drpFunction.Text = t; 
} 

但是不起作用。有什麼建議麼 ?

回答

23
string t = "test"; 
drpFunction.Items.FindByText(t).Selected = true; 
+1

這爲我工作。就我而言,我有一個只允許選擇單個項目的下拉菜單。這可能值得一提;如果當前選擇某個項目,則必須先取消選擇所選選項,否則將拋出異常,指示無法選擇多個項目。 'YourDropDownListId.ClearSelection();' – 2014-12-09 21:24:36

1

Link可以幫助你

public static void SelectText(this DropDownList bob, string text) 
{ 
    try 
    { 
     if (bob.SelectedIndex >= 0) 
      bob.Items[bob.SelectedIndex].Selected = false; 
     bob.Items.FindByText(text).Selected = true; 
    } 
    catch 
    { 
     throw new GenericDropDownListException("value", text); 
    } 
} 
-1

使用此...

protected void Page_Load(object sender, EventArgs e) 
{ 
    string t = "test"; 
    drpFunction.SelectedItem.Text = t; 
} 

protected void Page_Load(object sender, EventArgs e) 
{ 
    string t = "test"; 
    drpFunction.SelectedItem.Value = t; 
} 

這是正確的方式.......

0

我認爲屬性應該做你需要的。

0

該作品在網絡

ListItem li=new ListItem(); 

li.Text="Stringxyz"; 
li.Value="Stringxyz";  // Create object of item first and find its index. 

DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(li); 

這也能正常工作。

4

設置itm.Selected = true;只有在您首先使用drp.ClearSelection()時纔有效。 我更喜歡以下內容:

drpFunction.SelectedValue = drpFunction.Items.FindByText(t).Value; 
0
protected void Page_Load(object sender, EventArgs e) 
{ 
    string t = "test"; 
    drpFunction.SelectedValue = t; 
} 

SelectedValue屬性可以通過使用與項目的價值將它設置爲在列表中選擇控件中的項。但是,如果所選值與下拉列表中的值列表不匹配,則會發生異常。

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedvalue(v=vs.110).aspx

+0

你應該解釋你的答案,而不是隻發佈一段代碼。 – 2014-08-19 23:21:48

+0

@ChrisLoonam你是對的。 – JimmyBytes 2014-08-20 01:48:37

3
drpFunction.SelectedValue = drpFunction.Items.FindByText(t).Value; 

這是更好的方式來選擇文本。通過ioden的方式,它會顯示

「多項目不能在DropDownList中選擇」錯誤