Asker626 Asker626 - 17 days ago 4
C# Question

In C#- Retrieving data from selected item in combo box and fill into data grid view

I want to retrieve data from combo box and fill it into data grid view. I am using Visual Studio C# Windows Form. My application is using MySql database in retrieving data for column price, user, and date. I tried this code but It doesn't fill anything in data grid view. I have no problem filling my database at first but after I added the combo box to be filled in data grid view it didn't work.

Here's the code:

public void loadDataGridView_Main()
{
dgvMain.Rows.Clear();
List<string>[] detailList = a.mysqlSelect(comboProd.SelectedItem + "Select * From sales");
for (int i = 0; i < detailList.Length; i++)
{
dgvMain.Rows.Add(detailList[i][0], detailList[i][1], detailList[i][2], detailList[i][3]);
}
}


Automatically Load in Form.

private void frmMain_Load(object sender, EventArgs e)
{
a = new MyLibrary("localhost", "root", "", "cashieringdb");
loadDataGridView_Main();
dataLog();
fillCombo();
}


comboProd is the variable name for my
comboBox


Here's my
fillCombo
method I have no problem with this

public void fillCombo()
{
string MyConString = "SERVER=localhost;" +
"DATABASE=cashieringdb;" +
"UID=root;" +
"PASSWORD='';";
MySqlConnection connection = new MySqlConnection(MyConString);
string command = "select productAdd from settings";
MySqlDataAdapter da = new MySqlDataAdapter(command, connection);
DataTable dt = new DataTable();
da.Fill(dt);

comboProd.DataSource = dt;
comboProd.DisplayMember = "productAdd";
connection.Close();
}


This function is only for adding products and to be retrieved in
ComboBox
, for example if I add Apple product it will save into database and the
ComboBox
will retrieve the product apple to be added on the list.

EDIT

so here's the flow of my program.

in my data grid view I have 1
ComboBox
and 3 columns to be field in my data
GridView
. in the
ComboBox
it will fill my selected item in database side it will retrieve the value anything that is in the database. That is the reason I coded it this way.

List<string>[] detailList = a.mysqlSelect(comboProd.SelectedItem + "Select *


BUT I am not sure in this line. I am sceptical. I think the wrong is somewhere here.

Answer
private void frmMain_Load(object sender, EventArgs e)
{
    a = new MyLibrary("localhost", "root", "", "cashieringdb");
    fillCombo();   //fill combo before calling loadDataGridView_Main()
    loadDataGridView_Main();
    dataLog();    
}

Just replaced one statement. Now check it.