如何绑定产品名称,然后在标签结果中获取产品ID和价格?这三个属性来自DB中的同一个表。
代码:
public partial class CreateOrder : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false) bindListBox();
}
}
private void bindListBox()
{
ddlProduct.DataSource = getReader();
ddlProduct.DataTextField = "productName";
ddlProduct.DataValueField = "IDANDPRICE";
ddlProduct.DataBind();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT productName, productID,productPrice,(productID + '-' + productPrice) AS IDANDPRICE from Product";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "";
Label1.Text += "productName:" + ddlProduct.SelectedItem.Text + "<br/>";
Label2.Text = "";
Label2.Text += "IDANDPRICE:" + ddlProduct.SelectedItem.ToString() ;
}
答案 0 :(得分:0)
I find the following errors: 1- cast number filed to nvarchar in sql query 2- set AutoPostBack property of listbox to true 3- use ddlProduct.SelectedItem.Value for label2
我创建了一个页面并使用您的代码并应用了上述建议,以下代码完美无缺。
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false) bindListBox();
}
private void bindListBox()
{
ddlProduct.DataSource = getReader();
ddlProduct.DataTextField = "name";
ddlProduct.DataValueField = "IdAndName";
ddlProduct.DataBind();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT Id,Name,CAST( id as nvarchar(10) )+'-'+Name as IdAndName FROM Product";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "";
Label1.Text += "productName:" + ddlProduct.SelectedItem.Text + "<br/>";
Label2.Text = "";
Label2.Text += "IDANDPRICE:" + ddlProduct.SelectedItem.Value;
}
}