iT邦幫忙

0

C# Dropdownlist顯示MSSQL資料

大家好,小弟我是C#初心者,第一次上來發問,若排版及發問內容有哪些令人費解的地方
先跟大家說聲抱歉orz...

問題如下:

有兩個dropdownlist
1.customer的dropdownlist
2.plant的dropdownlist

以username對應,讓使用者依照table內username對應的customer來選取dropdownlist
選完customer後,也有該customer對應的plant

Table
customer username plant
A Jason O
B Jason X
B Jason P

以上面table為例
目前以下面方法實作遇到的問題:

  1. customer list 在選擇後會出現 A B B而希望顯示的結果是 A B
  2. customer list 在選擇後,因為用foreach寫的關係,每選一次選項就會增加
  3. plant list 在customer list選擇完後,選A只能看到O,但再選B的時候希望只能看到X與P,但上一次選的O也會繼續顯示。

不知道可以用甚麼方法來處理,麻煩各位大大指點迷津了,感謝!

 SqlConnection connSql = new SqlConnection(strConn);
                connSql.Open();
                string sql = "SELECT * from table";
                SqlCommand cmd = new SqlCommand(sql, connSql);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds, "cus");
                connSql.Close();
                foreach (DataRow r in ds.Tables["cus"].Rows)
                {
                    if (username.Text == r[2].ToString())
                    {
                        customer.Items.Add(r[1].ToString());

                        if (customer.Text == r[1].ToString())
                        {
                            plant.Items.Add(r[3].ToString());
                        }
                    }
                }

                cmd.Dispose();
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

5
Homura
iT邦高手 1 級 ‧ 2018-10-23 11:31:45
最佳解答

首先我看不懂你的Table的規劃

customer list 在選擇後會出現 A B B而希望顯示的結果是 A B

從這問題來看你應該要用2張表才對

table1

user customer
Jason A
Jason B
table2
customer plant
------- -----
A O
B X
B P

剛開始先塞好第1個dropdownlist的資料

SELECT customer FROM table1 WHERE user='Jason'

在選完第1個dropdownlist時觸發change事件
依照第1個dropdownlist的值來決定塞入第2個dropdownlist的值
這時要查詢第2張表,假如第1個dropdownlist選擇的是B

SELECT plant FROM table2 WHERE cutomer='B'

customer list 在選擇後,因為用foreach寫的關係,每選一次選項就會增加

你可以這樣寫,但是每次塞資料記得清空
比較好的寫法是直接塞進控制項的DataSource
然後DataBinding()

jason241 iT邦新手 5 級 ‧ 2018-10-23 13:48:58 檢舉

依大大所示,建立兩張table後,問題已順利解決,十分感謝!!

我要發表回答

立即登入回答