簡體   English   中英

使用 c# 從數據庫填充下拉列表,該下拉列表位於 Windows 應用程序中的 Gridview 中

[英]Populate dropdown from database, which is place inside Gridview in Windows Application using c#

如何從放置在 gridview 中的數據庫填充下拉列表,並使用 c# 在 windows 應用程序中處理該下拉列表的選定索引更改事件

您可以使用下拉框或組合框綁定 IList 實現。 您可以綁定任何 IList 並指定顯示屬性名稱,而不是 enum.getvalues。

DataGridViewComboBoxColumn CreateComboBoxWithEnums()
{
    DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
    combo.DataSource = Enum.GetValues(typeof(Title));
    combo.DataPropertyName = "Title";
    combo.Name = "Title";
    return combo;
}

然后使用下面的代碼將列添加到網格視圖列集合

dataGridView1.Columns.Add(CreateComboBoxWithEnums());

請注意,與 ComboBox 控件不同,DataGridViewComboBoxCell 沒有 SelectedIndex 和 SelectedValue 屬性。 相反,從下拉列表中選擇一個值會設置單元格的 Value 屬性。

參考: 本文檔

我希望您已經掌握了如何在 Datagridview 中填充組合框。 您可以嘗試使用此方法來處理 Datagridview Combobox 的選定索引更改,如下所示。

private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{           
        try
        {
            int column=excelGridview.CurrentCell.ColumnIndex;
            int row = excelGridview.CurrentCell.RowIndex;
            int country = Convert.ToInt32(((ComboBox)sender).SelectedValue);

            if (column == 7)
            {
                MyConnect myCnn = new MyConnect();  
                String connString = myCnn.getConnect().ToString();


                SqlConnection conn;
                SqlCommand command;
                conn = new SqlConnection(connString);
                command = new SqlCommand();


                if (country > 0)
                {
                    try
                    {
                        conn.Open();

                        string query = "select regionID FROM  countryinfo country  WHERE country.ID=" + country + "";

                        command = new SqlCommand(query, conn);

                        SqlDataReader reader = command.ExecuteReader();
                        DataTable dt = new DataTable();
                        dt.Load(reader);

                        var currentcell = excelGridview.CurrentCellAddress;
                        DataGridViewComboBoxCell cel = (DataGridViewComboBoxCell)excelGridview.Rows[currentcell.Y].Cells[8];

                        cel.Value = Convert.ToInt64(dt.Rows[0]["regionID"]);

                        conn.Close();

                    }
                    catch (Exception ex1)
                    {
                    }
                    finally
                    {
                        if (conn != null)
                        {
                            conn.Close();
                        }
                    }
                }
            }
        }
        catch (Exception) { }           
}

您可以從這里獲得幫助

它看起來如下圖所示

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM