Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I hve a small simple program I am working on just to get better at a few things and understand a little bit of code better. Its involving c# and SQL.
I have 2 database tables and they have a common field which is ORDERID. I have 2 controls in my C# program a combo box and a datagrid view. I have the combo box populated with all the orderids of one of the tables and I want my program to do this.
When I select a ordered in the combo box I want to populate the datagridview with all the specific orderids of the other table.
This is what I currently have and I was wondering if I can get help with this small simple task.

C#
//this populates the combo box with 1 tables order ids idk if this is the right way tho
public partial class MainWindow : Window
    {
        public static string connectionString= @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\CenturionDB.mdf;Integrated Security=True";

        public MainWindow()
        {
            InitializeComponent();

            using (SqlConnection sqlcon = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[Orders]", sqlcon);
                sqlcon.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while(reader.Read())
                {
                    ddlOrders.Items.Add(reader["OrderID"].ToString());
                }
                reader.Close();
            }
        }
//my database data
INSERT INTO [dbo].[Orders](OrderID, Type, Price) VALUES(1111, 'gG', 1.1)
INSERT INTO [dbo].[Orders](OrderID, Type, Price) VALUES(2222, 'BP', 1.2)
INSERT INTO [dbo].[Orders](OrderID, Type, Price) VALUES(3333, 'gG', 1.3)


INSERT INTO [dbo].[buys]( buysID, OrdersID, item, Type) VALUES(121, 1111, 'Monitor', 'gG')
INSERT INTO [dbo].[buys]( buysID, OrdersID, item, Type) VALUES(122, 1111, 'Keyboard', 'gG')
INSERT INTO [dbo].[buys]( buysID, OrdersID, item, Type) VALUES(131, 2222, 'TV', 'BP')
INSERT INTO [dbo].[buys]( buysID, OrdersID, item, Type) VALUES(132, 2222, 'Speakers', 'BP')
INSERT INTO [dbo].[buys]( buysID, OrdersID, item, Type) VALUES(141, 3333, 'sk8', 'sk8')
INSERT INTO [dbo].[buys]( buysID, OrdersID, item, Type) VALUES(142, 3333, 'bearings', 'sk8')
Posted

1 solution

Try this code at the click event of combobox

C#
try{
SqlCommand cmd1=new SqlCommand("Select * from buys where OrdersID="+ddlOrders.SelectedValue+"",sqlcon);
sqlcon.Open();
SqlDataReader readBuys = cmd1.ExecuteReader();
                while(readBuys.Read())
                {
datagridview1.Clear();
datagridview1.DataSource=readbuys;

}

}
catch(Exception exp)
{
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900