使用SQL DB表创建DropDown菜单C#

时间:2016-05-16 21:10:51

标签: c# sql wpf combobox datagrid

我需要你帮助处理我正在做的事情。

这很简单,但一直困扰着我。

我正在WPF应用程序中创建一个ComboBox [DropDown Menu],我想用我在数据库中拥有的所有当前表填充它。

这是我正在努力做的事情: 当我单击ComboBox时,它将显示DataBase中的所有可用表。然后,当我点击其中一个时,它将显示我放在菜单下面的DataGrid中所选表格中包含的信息。

My Application

这是我在ComboBox打开时使用的代码:

private void tableComboBox_DropDownOpened(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE';", db.connection);

        SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
        DataSet dataSet = new DataSet();
        dataAdapter.Fill(dataSet);

        foreach(DataRow row in dataSet.Tables)
        {
            tableComboBox.Items.Add(row);
        }
    }

我已经看过并尝试了一些不同的方法,但没有它们起作用。 我试图在DataGrid中显示表的内容,但我再次陷入困境。

请同伴们。在这里帮助这个新手! :)

2 个答案:

答案 0 :(得分:2)

所以这就是我很快想出来的。

  1. 删除tableComboBox_DropDownOpened事件。
  2. 添加事件comboBox_SelectionChange
  3. 更改数据库连接字符串,组合框和dataGrid的名称以匹配您的。
  4. 下面是代码,我将loadCombo()移到了你的初始化之下,以简化它。

        public partial class MainWindow : Window
    {
    SqlConnection db = new SqlConnection("Your Connection String Here");
    
        public MainWindow()
        {
            InitializeComponent();
    
            loadCombo();
        }
    
        private void loadCombo()
        {
            SqlCommand cmd = new SqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE';", db);
    
            SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
    
            foreach (DataRow row in dataSet.Tables[0].Rows)
            {
                comboBox.Items.Add(row[0]);
            }
        }
    
        private DataTable loadDataGrid(String inTableName )
        {
            SqlCommand cmd = new SqlCommand("SELECT COLUMN_NAME,* FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '"+ inTableName + "';", db);
    
            SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
    
            return dataSet.Tables[0];
        }
        private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string text = e.AddedItems[0].ToString(); ;
            dataGrid.ItemsSource = loadDataGrid(text).DefaultView;
        }
    }
    

    希望这有帮助

    我已在下面更新了您的代码。将其粘贴在一个镜头中。我不确定创建按钮发生了什么,但让我们看看我们是否可以修复组合框和数据网格。我在代码中添加了一些注释来帮助解释我的理性。

    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data;
    using System.Data.SqlClient;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace DatabaseManagement
    {
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Database db = new Database();
    
        public MainWindow()
        {
            InitializeComponent();
            // Add the loadCombo back
            loadCombo();
            // comment this out until you get the desired functionality  
            //TableCreateGrid.Visibility = Visibility.Hidden;
        }
    
        private void createButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
            // I am not sure what you are doing here -  
                if (string.IsNullOrEmpty(column3TextBox.Text) && string.IsNullOrEmpty(column4TextBox.Text))
                {
                    db.CreateTable(tableTextBox.Text, column1TextBox.Text, column2TextBox.Text);
    
                    informationBlock.Text = db.infoBoxString;
                }
    
                else if (string.IsNullOrEmpty(column4TextBox.Text))
                {
                    db.CreateTable(tableTextBox.Text, column1TextBox.Text, column2TextBox.Text, column3TextBox.Text);
    
                    informationBlock.Text = db.infoBoxString;
                }
    
                else if (!string.IsNullOrEmpty(column3TextBox.Text) && !string.IsNullOrEmpty(column4TextBox.Text))
                {
                    db.CreateTable(tableTextBox.Text, column1TextBox.Text, column2TextBox.Text, column3TextBox.Text, column4TextBox.Text);
    
                    informationBlock.Text = db.infoBoxString;
                }
            }
    
            catch (Exception ex)
            {
                informationBlock.Text = ex.Message;
            }
        }
    
        private void button_Click(object sender, RoutedEventArgs e)
        {
            db.Connect();
            informationBlock.Text = db.infoBoxString;
        }
    
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            db.Close();
            informationBlock.Text = db.infoBoxString;
        }
    
        private void loadCombo()
        {
            SqlCommand cmd = new SqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE';", db.connection);
    
            SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
    
            foreach (DataRow row in dataSet.Tables[0].Rows)
            {
                tableComboBox.Items.Add(row[0]);
            }
        }
    
        private DataTable loadDataGrid(String inTableName)
        {
            //  Here you need to specify the columns you want in the TableCreateGrid
            //  example  this just will show the COLUMN NAME,DATA TYPE, CHARACTER MAXIMUM LENGTH and so on
            //  SqlCommand cmd = new SqlCommand("SELECT COLUMN_NAME,DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, TABLE_SCHEMA FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + inTableName + "';", db.connection);
            SqlCommand cmd = new SqlCommand("SELECT COLUMN_NAME,* FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + inTableName + "';", db.connection);
    
            SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
    
            return dataSet.Tables[0];
        }
    
        private void tableComboBox_DropDownOpened(object sender, EventArgs e)
        {
            //loadCombo();
            // dont need since this is loaded on Initialize
        }
    
        private void tableComboBox_DropDownClosed(object sender, EventArgs e)
        {
          //  tableComboBox.Items.Clear();
          // dont need since this will clear all the items in the tableComboBox
        }
    
        private void tableComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                string text = e.AddedItems[0].ToString(); ;
                dataGrid.ItemsSource = loadDataGrid(e.AddedItems[0].ToString()).DefaultView;
            }
    
            catch (Exception ex)
            {
                informationBlock.Text = ex.Message;
            }
        }
    }
    }    
    

答案 1 :(得分:0)

  

这是用于在组合框中存储显式名称和值的代码

 private void Form1_Load(object sender, EventArgs e)
    {

        var Header = new BindingList<KeyValuePair<string, string>>();
        List<string> LV = ListHeader();
        foreach (var listOut in LV)
        {
            Header.Add(new KeyValuePair<string, string>(listOut, "val"+listOut));
        }
        tableComboBox.DataSource = Header;
        tableComboBox.DisplayMember = "Key";
        tableComboBox.ValueMember = "Value";
    }


public List<string> ListHeader()
{
    List<string> list = new List<String>();

    try
    {
        cmd.Connection = db.connection;

        cmd.CommandText = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE';";

        var reader = cmd.ExecuteReader();

          for(int i=0;i<reader.FieldCount;i++)
          {
            list.Add(reader.GetName(i));
          }

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Get Header",
             MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        con.Close();
    }

    return list;
}

你可以得到这样的组合框值:

  

Console.WriteLine(((KeyValuePair)tableComboBox.SelectedItem).Value.ToString());

或者您只想获得一个显示名称:

  

tableComboBox.SelectedItem.ToString()