gpt4 book ai didi

c# - 如何放置两个 DataValueField?

转载 作者:行者123 更新时间:2023-11-30 18:22:01 29 4
gpt4 key购买 nike

如何绑定(bind)产品名称,然后在标签结果中获取产品 ID 和价格?这三个属性来自数据库中的同一个表。

代码:

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() ;

}

最佳答案

I find the following errors:  1- cast number filed to nvarchar in sql query2- set AutoPostBack property of listbox to true3- use ddlProduct.SelectedItem.Value for label2

I create a page and use your code and apply above suggestion, the following code work perfectly.

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;
}

}

关于c# - 如何放置两个 DataValueField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34568338/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com