C# 在下拉列表中显示DB值

C# 在下拉列表中显示DB值,c#,asp.net,C#,Asp.net,我正在将数据库中的值显示到dropdownlist中。但是我无法将相应的值放入DDL中 if (dt.Rows.Count > 0) { DataTable dt1 = new DataTable(); dt1 = bll.getnewid(TextBox1.Text); if (dt1.Rows.Count > 0)

我正在将数据库中的值显示到dropdownlist中。但是我无法将相应的值放入DDL中

if (dt.Rows.Count > 0)
            {
                DataTable dt1 = new DataTable();
                dt1 = bll.getnewid(TextBox1.Text);

                    if (dt1.Rows.Count > 0)
                    {

                        Session["pid"] = dt1.Rows[0]["NewidColumn"].ToString();
                        Session["email"] = dt1.Rows[0]["EmailID"].ToString();
                        Session["gender"] = dt1.Rows[0]["Gender"].ToString();
                        Session["mobile"] = dt1.Rows[0]["MobileNo"].ToString();
                        Session["country"] = dt1.Rows[0]["Country"].ToString();
                        Session["state"] = dt1.Rows[0]["State"].ToString();
                      }
而我就是这样表现的

   DropDownList1.Text = Session["country"].ToString();
            DropDownList2.Text = Session["state"].ToString();
   DropDownList1.Items.Add("yourvalue");
   DropDownList1.Items.Add(Session["country"].ToString());

我能够在数据表中获得国家和州值。但是我无法在DDL中显示它们。

您需要设置dropdownlist的
SelectedValue
SelectedIndex
属性。

尝试这样做

   DropDownList1.Text = Session["country"].ToString();
            DropDownList2.Text = Session["state"].ToString();
DropDownList1.Items.Add(new ListItem(Session["country"].ToString()); 
DropDownList2.Items.Add(new ListItem(Session["state"].ToString());
   DropDownList1.Items.Add("yourvalue");
   DropDownList1.Items.Add(Session["country"].ToString());
请尝试以下代码:

DropDownList1.Items.Insert(0, new ListItem(Session["country"].ToString(), "0"));
DropDownList1.DataBind();

DropDownList2.Items.Insert(0, new ListItem(Session["state"].ToString(), "0"));
DropDownList2.DataBind();

使用会话的必要性是什么。。? 相反,试试这个……希望它能起作用。 在这行代码之后(dt1=bll.getnewid(TextBox1.Text);) 使用这两行代替会话

DropDownList1.DataSource=dt1;
DropDownList1.DataTextField="Country";
DropDownList1.DataValueField="Country";
DropDownList1.DataBind();
DropDownList2.DataSource=dt1;
DropDownList2.DataValueField="Country";
DropDownList2.DataValueField="Country";
DropDownList2.DataBind();

参数“1”:无法从“System.Web.UI.WebControls.ListItem”转换为“System.Web.UI.Control”我遇到类似这样的错误。此处国家/地区和州是数据表dt1中列的名称。确保列名与dt1匹配。我正在捕获国家和州值并显示在另一个页面中,因此我正在使用会话。你的意思是说选定的国家和州还是整个国家和州列表…?我正在填充由用户选择的DB中的值,并将其显示在DDL中,而不是列表中。从您编写的代码只会在会话中获取dt的第一行。相反,您不能在会话中存储dt并在访问值时将其键入datatable吗?当我这样做时,我会获取值,但在国家ddl中显示-选择一个国家-而不是国家名称,如何直接显示国家名称.DropDownList2.Items.Add(新列表项(会话[“ID”].ToString(),会话[“countryname”].ToString());什么是会话[“ID”]此处??我没有为其分配任何内容,可能会发生对象引用未设置为对象实例的错误。这意味着您必须向会话中添加联系人id。在使用之前,请添加此语句
DropDownList2.SelectedIndex=0;