2017-02-04 25 views
0

我試圖從下拉列表中讀取數值並將其顯示爲少數文本框。使用c#和MySQL作爲數據庫。從數據庫的下拉列表中選擇指定標識的值

我有三個表:產品,汽車,顏色。 有一個下拉列表和3個文本框。

我不知道如何將產品列入下拉菜單,並且在選擇產品後在每個文本框中顯示指定的「屬性」。

選擇產品1(下拉列表) - >顯示寶馬(1st文本框)綠色(第二個txtbox)。

每個產品都有靜態的「汽車」和「顏色」。產品的性質永遠不會改變。他們是獨特的。

+0

歡迎來到Stack Overflow!你可以先參加[遊覽]並學習[問]一個很好的問題,然後創建一個[mcve]。這使我們更容易幫助你。 – Katie

回答

0

拿這個例子

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 

Helper類

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

然後在你的EVET利用一切需要的東西。

相關問題