如何编写代码以从dropdownlist中的数据库中获取数据 [英] how to write code to fetch data from database in dropdownlist

查看:81
本文介绍了如何编写代码以从dropdownlist中的数据库中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写代码以从dropdownlist中的数据库中获取数据。文本框工作正常。





How to write code to fetch data from database in dropdownlist. Textboxes are working fine.


SqlCommand cmd = default(SqlCommand);
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Callregister_connectionstring"].ConnectionString);
        con.Open();
        cmd = new SqlCommand("Select * from Call_Reg where Complaint_no='" + ddlupCompl.SelectedItem.ToString() + "'", con);
        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            txtFname.Text = Convert.ToString(reader["Cust_FName"]);
            txtLname.Text = Convert.ToString(reader["Cust_LName"]);
            txtPh.Text = Convert.ToString(reader["ph_no"]);
            txtMob.Text = Convert.ToString(reader["mob_no"]);
            txtemail.Text = Convert.ToString(reader["email"]);
            txtadd.Text = Convert.ToString(reader["address"]);
            txtcity.Text = Convert.ToString(reader["city"]);
            txtdist.Text = Convert.ToString(reader["dist"]);
            
        }
            con.Close();

推荐答案

假设你有adropdownlistdrpCities您想使用此下拉列表显示城市列表。以下是示例代码:



Suppose you have adropdownlist "drpCities" you want to show city list using this dropdownlist. Here is the sample code:

SqlCommand cmd = default(SqlCommand);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Callregister_connectionstring"].ConnectionString);
con.Open();
cmd = new SqlCommand("Select cityId,cityName from City order by cityName", con);
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
drpCities.DataSource = dt.DefaultView;
drpCities.DataTextField = "cityName";
drpCities.DataValueField = "cityId";
drpCities.DataBind();


这是一个简单的例子:

here is the simple example:
cmd.CommandText = "Select field1, field2 from yourTable";
cmd.Connection = conn;
conn.Open();
DataTable dt  = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
DDownList1.DataSource = dt;
DDownList1.DataTextField = "field1";
DDownList1.DataValueField = "field2";
DDownList1.DataBind(); 


cmd.CommandText = " Select * From GetUsersID";
cmd.Connection = conn;
conn.Open();
DataTable dt  = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();


这篇关于如何编写代码以从dropdownlist中的数据库中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆