gpt4 book ai didi

c# - 从数据库下拉列表中选择的指定 ID 获取值

转载 作者:行者123 更新时间:2023-11-29 19:27:22 24 4
gpt4 key购买 nike

我正在尝试从下拉列表中读取值并显示到几个文本框中。使用c#和MySQL作为数据库。

我有三个表:产品、汽车、颜色。有 1 个下拉列表和 3 个文本框。

我不知道如何将产品列出到下拉列表中,以及选择产品后如何在每个文本框中显示指定的“属性”。

选择产品 1(下拉菜单)-> 将 BMW(第一个文本框)显示为绿色(第二个文本框)。

每个产品都有静态的“汽车”和“颜色”。产品的属性永远不会改变。他们是独一无二的。

最佳答案

举这个例子

Table 1 Product
id|name
--------
1 | Car
2 | car


Table 2 Type
id|model
--------
1 | BMW
2 | Mercedes

Table 2 Color
id|car_color
------------
1 | Green
2 | Yellow

辅助类

class MySQLClass : IDisposable
{
// Connection string need to be replaced for secure purpuose
private static string connString = @"Server=xxxx;uid=xxxx;pwd=xxxxx;database=xxxxxx";
/// <summary>
/// OdbcConnection : This is the connection
/// </summary>
SqlConnection oConnection;
/// <summary>
/// OdbcCommand : This is the command
/// </summary>
SqlCommand oCommand;
/// <summary>
/// Constructor: This is the constructor
/// </summary>
/// <param name="DataSourceName">string: This is the data source name</param>
public MySQLClass()
{
//Instantiate the connection
oConnection = new SqlConnection(connString);
try
{
//Open the connection
oConnection.Open();
//Notify the user that the connection is opened
//Console.WriteLine("The connection is established with the database");
}
catch (OdbcException caught)
{
Console.WriteLine(caught.Message);
Console.Read();
}
}
/// <summary>
/// void: It is used to close the connection if you work within disconnected
/// mode
/// </summary>
public void CloseConnection()
{
oConnection.Close();
}
/// <summary>
/// OdbcCommand: This function returns a valid odbc connection
/// </summary>
/// <param name="Query">string: This is the MySQL query</param>
/// <returns></returns>
public SqlCommand GetCommand(string Query)
{
oCommand = new SqlCommand();
oCommand.Connection = oConnection;
oCommand.CommandText = Query;
return oCommand;
}
/// <summary>
/// void: This method close the actual connection
/// </summary>
public void Dispose()
{
oConnection.Close();
}
}

使用

DataTable dt = new DataTable();
using (MySQLClass o = new MySQLClass())
{
string sql = @"
SELECT Product.id, Product.name, Type.model, Color.car_color FROM Product
INNER JOIN Type ON Product.id = Type.id
INNER JOIN Color ON Type.id = Color.id;

";
SqlCommand oCommand = o.GetCommand(sql);
SqlDataAdapter adapter = new SqlDataAdapter(oCommand);
adapter.Fill(dt);


// ddList is your dropDownList
ddList.DataSource = dt;
ddList.DataTextField = "name";
ddList.DataValueField = "id";
ddList.DataBind();
}

然后在你的夜晚使用你需要的一切。

关于c# - 从数据库下拉列表中选择的指定 ID 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42042308/

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