大家好我对下拉列表有疑问。我正在使用带数据源的下拉列表。我怎样才能获得我选择的那个值?
// I need a if statement here because my programme doesn't know which value of dropdown list selected and I don't know how to use this with datasource.
if(//if I select quiz 1 from dropdown list ,quiz 1 should list questions.)
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);
string chooce = "Select Quiz from tblQuiz where Quiz=1 ";
SqlCommand userExist = new SqlCommand(chooce, con);
con.Open();
int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
if (temp == 1)
{
if (rbList.Items[0].Selected == true)
{
string cmdStr = "Select Question from tblQuiz where ID=1";
SqlCommand quest = new SqlCommand(cmdStr, con);
lblque.Text = quest.ExecuteScalar().ToString();
con.Close();
}
答案 0 :(得分:30)
您可以使用List, Dictionary, Enum, DataSet DataTable
以不同方式绑定DropDownList。
主要是在绑定下拉列表的数据源时必须考虑三件事。
您可以使用以下代码将下拉列表绑定到数据源datatable
:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
DropDownList1.DataTextField = "QUIZ_Name";
DropDownList1.DataValueField = "QUIZ_ID"
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
如果您想要选择下拉列表,则必须更改AutoPostBack="true"
,您可以使用SelectedIndexChanged
事件来编写代码。
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strQUIZ_ID=DropDownList1.SelectedValue;
string strQUIZ_Name=DropDownList1.SelectedItem.Text;
// Your code..............
}
答案 1 :(得分:4)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
drpCategory.DataSource = CategoryHelper.Categories;
drpCategory.DataTextField = "Name";
drpCategory.DataValueField = "Id";
drpCategory.DataBind();
}
}
答案 2 :(得分:2)
请参阅此链接中的示例。它可能会对你有所帮助。
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx
void Page_Load(Object sender, EventArgs e)
{
// Load data for the DropDownList control only once, when the
// page is first loaded.
if(!IsPostBack)
{
// Specify the data source and field names for the Text
// and Value properties of the items (ListItem objects)
// in the DropDownList control.
ColorList.DataSource = CreateDataSource();
ColorList.DataTextField = "ColorTextField";
ColorList.DataValueField = "ColorValueField";
// Bind the data to the control.
ColorList.DataBind();
// Set the default selected item, if desired.
ColorList.SelectedIndex = 0;
}
}
void Selection_Change(Object sender, EventArgs e)
{
// Set the background color for days in the Calendar control
// based on the value selected by the user from the
// DropDownList control.
Calendar1.DayStyle.BackColor =
System.Drawing.Color.FromName(ColorList.SelectedItem.Value);
}
答案 3 :(得分:0)
这取决于您如何设置下拉列表的默认值。使用所选值,但您必须设置所选值。例如,我使用表/列表的名称和id字段填充数据源。我将所选值设置为id字段,将显示设置为名称。当我选择时,我得到了id字段。我用它来搜索关系表并找到一个实体/记录。