2016-09-23 49 views
2

我有一个充满就像一个下拉列表:C#的DropDownList上市数值

cmd.CommandText = "select * from dbo.pelischool"; 
         SqlDataAdapter da = new SqlDataAdapter(cmd); 
         DataSet ds = new DataSet(); 
         da.Fill(ds); 
         DropDownList1.DataTextField = ds.Tables[0].Columns["schoolName"].ToString(); 
         DropDownList1.DataSource = ds.Tables[0]; 
         DropDownList1.DataBind(); 

现在我想读(以将其放置在一个查询)所选项目的上市数量。 因此,虽然我的下拉列表具有“牛津大学”,“麻省理工大学”,“西蒙弗雷泽大学”等价值观,但我希望单击列表中的项目,将此项目的值存储在列表中。更具体地讲,如果单击第一个项目,然后 INT数= 1。如果单击第二个项目,然后 INT数= 2

是否有可能与像做:

DropDownList1.SelectedItem.????; 

谢谢你的时间!

+1

您必须对数据库中的每个schoolName一定的价值的价值。将这些值绑定到DropDownList1.DataValueField中。 –

回答

2

如果你想选择的值,然后使用

DropDownList1.SelectedValue 

,如果你想选择的项目,然后用

DropDownList1.SelectedItem 
0
cmd.CommandText = "select * from dbo.pelischool"; 
          SqlDataAdapter da = new SqlDataAdapter(cmd); 
          DataSet ds = new DataSet(); 
          da.Fill(ds); 
          DropDownList1.DataTextField = ds.Tables[0].Columns["schoolName"].ToString(); 
          DropDownList1.DataValueField = ds.Tables[0].Columns["SomeValueColumn or id column"]; 
          DropDownList1.DataSource = ds.Tables[0]; 
          DropDownList1.DataBind(); 

,然后可以使用...

string id = DropDownList1.SelectedValue.ToString(); 

试试这个。

cmd.CommandText = "select id,schoolName from dbo.pelischool"; 
SqlDataAdapter da = new SqlDataAdapter(cmd); 
DataTable dt = new DataTable(); 
da.Fill(dt); 
if (dt != null) 
     { 
      if (dt.Rows.Count > 0) 
      { 
       ddlPosition.DataSource = dt; 
       ddlPosition.DataTextField = "schoolName"; 
       ddlPosition.DataValueField = "Id"; 
       ddlPosition.DataBind(); 
      } 
     } 
+0

这似乎是好的,但由于某种原因(奇怪)总是存储第一个ID。即使我选择第二个或第三个下拉选项,它也会存储第一个的编号 – George

+0

我已经更新了我的答案。请试试这个。我希望它会帮助你 –

+0

也请分享你的pelischool表值。因此,解决你的问题兄弟会更容易。 –

0

除了尼廷·库马尔回答,所选项目的文本可以通过以下方式获得:

var selectedText = DropDownList1.SelectedItem.Text; 

选定值

var selectedValue = DropDownList1.SelectedValue; 
3

你没有bind项目的价值dropdownlist,所以你需要绑定它。

这样

DropDownList1.DataValueField = ds.Tables[0].Columns["Column name that contain the value of Item"].ToString(); 

,然后你可以用它来得到它就像如下

string item_value = DropDownList1.SelectedValue; 
+0

已经这样做了,但出于某种原因,我总是得到第一个项目的ID。它总是1,无论我选择哪个项目 – George

+0

请显示你的代码,你用来获得项目的值 –

+0

' SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); DropDownList1.DataTextField = ds.Tables [0] .Columns [“schoolName”]。ToString(); DropDownList1.DataValueField = ds.Tables [0] .Columns [“schoolID”]。ToString(); DropDownList1.DataSource = ds。表[0]; DropDownList1.DataBind();' – George