怎样使用DROPDOWNLIST绑定数据返回选择行
展开全部
首先在web.config创建一个键值。
<appSettings>
<add key="CONNSTR" value="server=(local);database=Test;user id=sa;"/>
</appSettings>
在.aspx.cs的命名空间上加上下面三个:
using System.configuration;
using System.Data;
using System.Data.SqlClient;
下面是绑定DropDownList:
protected void Init_Data()
{
string ConnStr = ConfigurationManager.AppSettings["ConnStr"].ToString();
SqlConnection conn = new SqlConnection(ConnStr);
try
{
conn.Open();//打开数据连接
}
catch
{
Response.Write("错误");
}
SqlCommand Cmd = new SqlCommand("select * from tablename", conn);
SqlDataReader myRd = Cmd.ExecuteReader();
DDLName.DataSource = myRd;
DDLName.DataTextField = "name";//要绑定的字段
DDLName.DataValueField = "id";//要绑定的ID
DDLName.DataBind();
conn.Close();
myRd.Close();
DDLName.Items.Insert(0, "请选择");
}
protected void Button1_Click(object sender, EventArgs e)
{
string ConnStr = ConfigurationManager.AppSettings["ConnStr"].ToString();
SqlConnection conn = new SqlConnection(ConnStr);
conn.Open();
for (int i = 1; i < DDLName.Items.Count; i++)
{
if (DDLName.Items[i].Selected == true) //判断谁被选中
{
string selSql="select * from tablename where ID='"+DDLName.SelectedValue+"'";
SqlCommand mycmd=new SqlCommand(selSql,conn);
SqlDataReader myrd=mycmd.ExecuteReader() ;
while(myrd.Read())
{
Response.Write(....);//打印
}
}
}
}
<appSettings>
<add key="CONNSTR" value="server=(local);database=Test;user id=sa;"/>
</appSettings>
在.aspx.cs的命名空间上加上下面三个:
using System.configuration;
using System.Data;
using System.Data.SqlClient;
下面是绑定DropDownList:
protected void Init_Data()
{
string ConnStr = ConfigurationManager.AppSettings["ConnStr"].ToString();
SqlConnection conn = new SqlConnection(ConnStr);
try
{
conn.Open();//打开数据连接
}
catch
{
Response.Write("错误");
}
SqlCommand Cmd = new SqlCommand("select * from tablename", conn);
SqlDataReader myRd = Cmd.ExecuteReader();
DDLName.DataSource = myRd;
DDLName.DataTextField = "name";//要绑定的字段
DDLName.DataValueField = "id";//要绑定的ID
DDLName.DataBind();
conn.Close();
myRd.Close();
DDLName.Items.Insert(0, "请选择");
}
protected void Button1_Click(object sender, EventArgs e)
{
string ConnStr = ConfigurationManager.AppSettings["ConnStr"].ToString();
SqlConnection conn = new SqlConnection(ConnStr);
conn.Open();
for (int i = 1; i < DDLName.Items.Count; i++)
{
if (DDLName.Items[i].Selected == true) //判断谁被选中
{
string selSql="select * from tablename where ID='"+DDLName.SelectedValue+"'";
SqlCommand mycmd=new SqlCommand(selSql,conn);
SqlDataReader myrd=mycmd.ExecuteReader() ;
while(myrd.Read())
{
Response.Write(....);//打印
}
}
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询