0

I make wpf database app and I want to select table from my database with combobox.

I have a database with ten tables. I can connect to the database and I can select/updata/insert... items from a table. I need to switched between tables. For examp, if I click to Table1, Table1 will selected, if I click to Table2, Table2 will selected. Combobox is good for my app, I believe. This is my code for select:

public MainWindow()
        {
            InitializeComponent();
            loadData();
        }

        public void loadData()
        {
            // vytvoření spojení
            MySqlConnection con = new MySqlConnection(spojeni);
            con.Open();

            MySqlCommand vybrat = con.CreateCommand();     
            vybrat.CommandText = "SELECT * FROM barva";        
            MySqlDataAdapter adapt = new MySqlDataAdapter(vybrat);        
            DataSet data = new DataSet();

            adapt.Fill(data);           
            dtGrid.ItemsSource = data.Tables[0].DefaultView;
          }

PS. I apologize for my English

4
  • Create a public list of the table names in your C#, and another public string for the Selected Item, bind a combo box to them, and use that in the SQL. Commented May 20, 2019 at 12:56
  • I know I have to do something like that, but I don't know how. I'm a really bad programmer. This is my combobox: <ComboBox x:Name="CbTabulky" > <ComboBoxItem Name="cbi">konzole</ComboBoxItem> <ComboBoxItem Name="cbi2">výrobce</ComboBoxItem> <ComboBoxItem Name="cbi3">platforma</ComboBoxItem> </ComboBox> Commented May 21, 2019 at 6:51
  • Here's an example of how to bind a combobox to a list: stackoverflow.com/questions/21898022/… Commented May 21, 2019 at 7:59
  • I read the examples but I still don't understand. If I send you a link to my project, can you explain it to me, please? Commented May 21, 2019 at 13:54

2 Answers 2

0

Here's a really simple example of binding a combobox to a list of strings, and using the selected string when a button is pressed.

This is the C# code-behind file:

using System.Collections.Generic;
using System.Windows;

namespace WpfCombobox
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
        }

        public string MySimpleStringProperty { get; set; }

        public List<string> MyListProperty { get; set; } = new List<string>() { "one", "two", "three" };

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            MessageBox.Show($"Item is {this.MySimpleStringProperty}");
        }
    }
}

Obviously, instead of just displaying the selected item in a message box, you'd use it in your SQL.

And here's the WPF:

<Window x:Class="WpfCombobox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfCombobox"
        mc:Ignorable="d"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <ComboBox ItemsSource="{Binding MyListProperty}" 
                  SelectedItem="{Binding MySimpleStringProperty}" 
                  IsSynchronizedWithCurrentItem="True" 
                  Text="Select Option"
                  Margin="5"/>
        <Button Click="ButtonBase_OnClick" Content="Click Me!" Margin="5" />
    </StackPanel>
</Window>

Notice that the combobox has an ItemSource, which is bound to the list of strings one, two, three, and a SelectedItem, which changes when the user picks an item.

Sign up to request clarification or add additional context in comments.

4 Comments

Oh, I see. Thank you, I'll try it.
It works great, thank you. I have the last question: How can I create a dynamic TextBox? I tried something, but it didn't work correct.
What do you mean by 'dynamic'? Do you want to create a control at run-time, rather than code It in the XAML? This example might help: stackoverflow.com/questions/12468658/… Otherwise, you should ask a new question.
Yes, I mean something like this, but it don't work form me. I'll try to ask a new question. Thank you again for your help.
0

I guess you're looking for something like this (connection string belongs under configuration on web.config):

<connectionStrings>
  <add name="YOUR CONNECTION" connectionString="Data Source= ;Initial Catalog= ; User ID= ;Password= ;" providerName="System.Data.SqlClient" />
</connectionStrings>
//Connection to Web.config connectionStrings
DataTable database = new DataTable();
string dbString = ConfigurationManager.ConnectionStrings["YOUR CONNECTION"].ConnectionString;
using (SqlConnection con = new SqlConnection(dbString))
{
    try
    {
        //SQL query
        SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM sys.tables", con);
        adapter.Fill(database);

        //Populate ddlTable DropDownList
        ddlTable.DataSource = database;
        ddlTable.DataTextField = "name";
        ddlTable.DataValueField = "name";
        ddlTable.DataBind();
        ddlTable.Items.Insert(0, new ListItem("-- Select Table --", "0"));
    }
    catch (Exception)
    {

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.