如何将数据绑定到下拉列表
问题描述:
嗨
我使用一个下拉列表框(用户ID)和两个文本框(名字和姓氏).
然后选择Userid,然后使用Sql server将数据绑定到名字和姓氏.
谢谢.
Hi
I use one drop downlist box(user id) and two textbox(First Name and Last Name).
And I Select Userid And Then bind the data To First Name And Last Name Using Sql server.
Thanking You.
答
阿伦,
Hi Arun,
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class Default3 : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string str;
SqlCommand com;
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.AutoPostBack = true;
SqlConnection con = new SqlConnection(strConnString);
if (!IsPostBack)
{
DropDownList1.Items.Add("Choose userid");
con.Open();
str = "select * from Contacts";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
DropDownList1.Items.Add(reader["userid"].ToString());
}
reader.Close();
con.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
str = "select * from Contacts where userid=''" + DropDownList1.SelectedItem.Text + "''";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
TextBox1.Text=reader["Fname"].ToString();
TextBox2.Text = reader["Lname"].ToString();
}
reader.Close();
con.Close();
}
}