2016-11-28 72 views
0

這是我的代碼,將表值顯示爲DropDownList獲取asp.net中selectedIndex變化事件下拉列表中第三列的值

using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString)) 
{ 
    con.Open(); 
    string str="SELECT ItemOne,ItemTwo,ItemThree FROM tableItem"; 
    using (SqlCommand cmd = new SqlCommand(str, con)) 
    { 
     SqlDataAdapter dA=new SqlDataAdapter(cmd); 
     dA.Fill(dT); 
     DropDownList1.DataSource = dT; 
     DropDownList1.DataValueField = "ItemTwo"; 
     DropDownList1.DataTextField = "ItemOne"; 
     DropDownList1.DataBind(); 
    } 

這是的DropDownList選擇的值顯示給TextBox

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
     TextBox1.Text = DropDownList1.SelectedValue.ToString(); 
     TextBox2.Text = //Get the value of ItemThree here 
} 

我的問題是:我將如何顯示ItemThree在另一TextBox列值。

回答

0

從事件處理程序這樣

var connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString; 
var sql = "SELECT ItemOne, ItemTwo, ItemThree FROM tableItem"; 
using (var table = new DataTable) { 
    using (var adapter = new SqlDataAdapter(sql, connectionString) 
     adapter.Fill(table); 
    foreach (DataRow dr in table.Rows) 
     DropDownList1.Items.Add(new ListItem(dr["ItemTwo"], dr["ItemTwo"]) { 
      Tag = dr["ItemThree"] 
     }); 
} 

接着的另一種方式

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
     TextBox1.Text = DropDownList1.SelectedValue.ToString(); 
     TextBox2.Text = DropdownList1.SelectedItem.Tag.ToString(); 
} 
+0

無法應用用[]索引到類型「對象」誤差的表達出現 –

+0

@odlanyer更正。 – Shreevardhan

0
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     TextBox1.Text = DropDownList1.SelectedValue.ToString(); 
     TextBox2.Text = DropDownList1.Items[2].ToString(); // 2 is your index 
    } 
+0

儘管此代碼片段可能會解決問題,但其中的解釋確實有助於提高帖子的質量 – Zety

+0

這隻適用於第一次選定的事件點擊,但在成功點擊後無法使用。 –

相關問題