I'm trying to add a combo Box to the datagrid View. This is the code for the datagrid view
SqlDataAdapter da = new SqlDataAdapter("SELECT pid, pdtName, amount, Qty,day, cat from purchase where year=#year and month=#month", ConnectionInfo.con);
da.SelectCommand.Parameters.AddWithValue("#year", comboBox3.Text);
da.SelectCommand.Parameters.AddWithValue("#month", comboBox2.Text);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
this.dataGridView1.Columns[0].HeaderText = "number";
this.dataGridView1.Columns[0].ReadOnly = true;
this.dataGridView1.Columns[0].Visible = false;
this.dataGridView1.Columns[1].HeaderText = "name";
this.dataGridView1.Columns[2].HeaderText = "amount";
this.dataGridView1.Columns[3].HeaderText = "number";
this.dataGridView1.Columns[4].HeaderText = "day";
this.dataGridView1.Columns[5].HeaderText = "category";
for column 5 in the datagrid view I'm trying to set it as a combo box and read the category names from the category table in my database.
I'm starting with this code but I don't know how to complete it
string query = "select distinct cat from purchase ";
SqlDataAdapter da2 = new SqlDataAdapter(query, ConnectionInfo.con);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "purchase");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.HeaderText = "cat";
cmb.Name = "cmb";
cmb.DataSource=ds2
Can you point out whats wrong in my code, or help me in another way to solve my problem
You need to format each column using a DataGridViewTextBoxColumn or DataGridViewComboBoxColumn and add it to the DataGridView. Be sure to set AutoGenerateColumns to false. Something like:
dataGridView1.Columns.Clear();
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Description";
column.Name = "Description";
column.HeaderText = "Description";
column.Width = 150;
//column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns.Add(column)
DataGridViewComboBoxColumn ccolumn = new DataGridViewComboBoxColumn();
ccolumn.DataPropertyName = "cmb";
ccolumn.Name = "cmb";
ccolumn.HeaderText = "Cat";
ccolumn.Width = 65;
ccolumn.DataSource = ds2;
ccolumn.DisplayMember = "cat";
ccolumn.ValueMember = "cat";
dataGridView1.Columns.Add(ccolumn);
Do all the columns like this before you assign the DataSource to the DataGridView.
Related
I have a table as following in SQL Database. Devicereg Table.
No | Parameter | DataTyp | Enable |
1 xxxx Int True
2 yyyy Int True
3 tttt String False
I want to show these data in DataGridView and its DataTyp column want to add Combobox with default value table cell value, Enable column want to add a checkbox with default value table cell value.
Combobox want to add the following list and the default value is one of following value.
Int
String
Floart
Following code, Combobox value adds all columns value in one combo box.
Code:
string connetionString = null;
SqlConnection connection;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
bool st = false;
DataSet ds = new DataSet();
connection = new SqlConnection(connetionString);
sql = "select * from Devicereg";
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand(sql, connection);
adapter.Fill(ds);
connection.Close();
dataGridView1.DataSource = null;
dataGridView1.ColumnCount = 0;
dataGridView1.DataSource = ds.Tables[0];
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = ds.Tables[0];
dc.ValueMember = "Datatyp";
dataGridView1.Columns.Add(dc);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Example Photo:
Edit 1:
I have done it but how to display only defined items in the dropdown.
Code:
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = ds.Tables[0];
dc.DataPropertyName = "Datatyp";
dc.ValueMember = "Datatyp";
dc.DisplayMember = "Datatyp";
I have 36 rows and all rows Datatyp values shows. I want specific items to select like Int, Flort, Strings only.
Output:
Edit 2:
If I set like the following code, I got error message.
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = new List<string> { "Int", "String", "Flort" };
dc.DataPropertyName = "Datatyp";
dc.ValueMember = "Datatyp";
dc.DisplayMember = "Datatyp";
Error:
To import the DataTyp from database to DataGridViewComboBoxColumn, please refer to the following steps.
First, add the columns to datagridview.
Set the DataTyp's columntype to DataGridViewComboBoxColumn, and set its DataSource like:
Next, set Enable columntype to DataGridViewCheckBoxColumn.
Or via code:
var colNo = new DataGridViewTextBoxColumn
{
HeaderText = "No",
Name = "No"
};
var colParameter = new DataGridViewTextBoxColumn
{
HeaderText = "Parameter",
Name = "Parameter"
};
var colDataTyp = new DataGridViewComboBoxColumn
{
HeaderText = "DataTyp",
Name = "DataTyp",
DataSource = new List<string> { "Int", "String", "Float" }
};
var colEnable = new DataGridViewCheckBoxColumn
{
HeaderText = "Enable",
Name = "Enable"
};
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { colNo, colParameter, colDataTyp, colEnable });
Then fill the datagridview via the code below.
DataSet ds;
string connetionString = #"Connection String";
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From Devicereg", conn);
ds = new DataSet();
sda.Fill(ds, "T1");
}
DataGridViewComboBoxCell typeCell;
foreach (DataRow row in ds.Tables[0].Rows)
{
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells["No"].Value = row[0];
dataGridView1.Rows[index].Cells["Parameter"].Value = row[1];
typeCell = (DataGridViewComboBoxCell)(dataGridView1.Rows[index].Cells["DataTyp"]);
typeCell.Value = row[2].ToString().Trim();
dataGridView1.Rows[index].Cells["Enable"].Value = row[3];
}
The result,
I`m having a problem displaying some data on a datagrid view. I send data to MySQL on form2 and then its supposed to be displayed in a datagrid view in form1. The datagrid view is updating perfectly but it seems that the datatable is not getting populated with the full information. There are 2 rows of data that should be displayed. I get 2 empty rows in datagrid view.I checked the database and the information is there. Is it my query that isnt right?
What I need are all the rows that have temp_quote.quote_id in the quotes_idquotes column. Can you help me out? Here is the code:
public void RefreshGrid_parts()
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from shopmanager.parts where quotes_idquotes = '" + temp_quote.quote_id + "';",con);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.AutoGenerateColumns = false;
dataGridView1.ColumnCount = 6;
dataGridView1.Columns[0].HeaderText = "# Assembly";
dataGridView1.Columns[0].DataPropertyName = "assemblies_assembly_id";
dataGridView1.Columns[1].HeaderText = "# Part";
dataGridView1.Columns[1].DataPropertyName = "part_number";
dataGridView1.Columns[2].HeaderText = "# Item";
dataGridView1.Columns[2].DataPropertyName = "items_items_id";
dataGridView1.Columns[3].HeaderText = "# Description";
dataGridView1.Columns[3].DataPropertyName = "part_description";
dataGridView1.Columns[4].HeaderText = "Drawing Revision";
dataGridView1.Columns[4].DataPropertyName = "drawing_rev";
dataGridView1.Columns[5].HeaderText = "Quantity";
dataGridView1.Columns[5].DataPropertyName = "quantity";
dataGridView1.DataSource = dt;
con.Close();
}
Here is your property example:
(yes its mssql but the logic is the same just change the types, I don't have the mysql lib at hand right know. i guess you'll figure it out.)
SqlClient.SqlCommand comand = new SqlClient.SqlCommand("Select * From ExampleTable Where Colum1 = $1");
comand.Parameters.Add(new SqlClient.SqlParameter("$1", "1234") { DbType = DbType.Int32 });
this will also parse the decimal string into the correct data type (int32)
Try to comment the lines that create the headers to test if your data will appear in the DataGrid. Also put the AutoGenerateColumns to true. If it does, check the DataPropertyName if it's exactly the names of the columns on your query.
public void RefreshGrid_parts()
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from shopmanager.parts where quotes_idquotes = '" + temp_quote.quote_id + "';",con);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.AutoGenerateColumns = true;
//dataGridView1.ColumnCount = 6;
//dataGridView1.Columns[0].HeaderText = "# Assembly";
//dataGridView1.Columns[0].DataPropertyName = "assemblies_assembly_id";
//dataGridView1.Columns[1].HeaderText = "# Part";
//dataGridView1.Columns[1].DataPropertyName = "part_number";
//dataGridView1.Columns[2].HeaderText = "# Item";
//dataGridView1.Columns[2].DataPropertyName = "items_items_id";
//dataGridView1.Columns[3].HeaderText = "# Description";
//dataGridView1.Columns[3].DataPropertyName = "part_description";
//dataGridView1.Columns[4].HeaderText = "Drawing Revision";
//dataGridView1.Columns[4].DataPropertyName = "drawing_rev";
//dataGridView1.Columns[5].HeaderText = "Quantity";
//dataGridView1.Columns[5].DataPropertyName = "quantity";
dataGridView1.DataSource = dt;
con.Close();
}
maybe take Rodrigos suggestion and just let the control generate the columns.
if you want to only this six columns just change the query.
public void RefreshGrid_parts()
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
con.Open();
MySqlCommand cmd = new MySqlCommand("select assemblies_assembly_id as '# Assembly', part_number as '# Part', items_items_id as '# Item', part_description as '# Description', drawing_rev as 'Drawing Revision', quantity as 'Quantity' from shopmanager.parts where quotes_idquotes = $1;",con);
cmd.Parameters.Add(new MySqlParameter("$1", temp_quote.quote_id) { DbType = DbType.Int32 });
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
con.Close();
}
I feel like an idiot. The code is good. The problem was that the text color in the datagrid view was white in a white box so I could not see it. Sorry to have bothered you guys with this. 24 hours spent on a non-existing problem! Wow!
Though I set a new column header in datatable before assigning it to datagridview, when I call this datagridview from dataview I get old column headers. Here is a part of my code:
DataSet ds = new DataSet();
grid.DataSource = null;
ds.ReadXml(path);
var dt = ds.Tables[0];
dt.Columns["Name"].Caption = "Descr";
dt.Columns["Account"].Caption = "ACNT"; // I tried both .Caption and .Columname
grid.DataSource = ds.Tables[0];
I also tried changing column header after implementation of datagridview, but still without any result:
grid.Columns[0].HeaderText = "Descr";
How can I set a column header that later dataview can read it properly?
you need to set the DataPropertyName, in your case:
dt.Columns["Name"].DataPropertyName = "Name";
dt.Columns["Name"].HeaderText = "Descr";
dt.Columns["Account"].DataPropertyName = "Account";
dt.Columns["Account"].HeaderText = "ACNT";
You could try the following below:
grid.DataSource = null;
using (DataSet ds = new DataSet())
{
ds.ReadXml(path);
var dt = ds.Tables[0];
sda.Fill(dt);
//Set AutoGenerateColumns False
dataGridView1.AutoGenerateColumns = false;
//Set Columns Count
dataGridView1.ColumnCount = 3;
//Add Columns
dataGridView1.Columns[0].Name = "CustomerId";
dataGridView1.Columns[0].HeaderText = "Customer Id";
dataGridView1.Columns[0].DataPropertyName = "CustomerID";
dataGridView1.Columns[1].HeaderText = "Contact Name";
dataGridView1.Columns[1].Name = "Name";
dataGridView1.Columns[1].DataPropertyName = "ContactName";
dataGridView1.Columns[2].Name = "Country";
dataGridView1.Columns[2].HeaderText = "Country";
dataGridView1.Columns[2].DataPropertyName = "Country";
dataGridView1.DataSource = dt;
}
}
Another way,you could try with less lines of code. Use the Design view yourGrid->smart tag -> edited the column ->Data->DataProperty ->(Add your db column Name).
Once that is Done you can just call your grid.
private void PopulateGrid()
{
grid.AutoGenerateColumns = false;
List<Your table> yourTable_List = GetMethodOfTheData();
var source = new BindingSource(yourTable_List , null);
grid.DataSource = source;
}
I am failing to bind text boxes to a dataset. It says saving1(mytablename) can't create child list. Here is the code; basically the problem is in the text boxes down where I have put the ********:
DataSet myDataset = new DataSet("saving1");
DataSet myDataset2 = new DataSet();
myDataAdapter.Fill(myDataset, "saving1");
myDataAdapter2.Fill(myDataset2, "extrasave");
dataGridView1.DataSource = myDataset.Tables["saving1"];
dataGridView3.DataSource = myDataset2.Tables["extrasave"];
myDataset2.Merge(myDataset);
dataGridView2.DataSource = myDataset.Tables["saving1"];
// Use the DataMember property to specify the DataTable.
dataGridView2.DataMember = "saving1";
//dataGridView1.SetDataBinding(ds, "saving1");
//comboBox2.DataSource = ds;
// comboBox2.DisplayMember = "items";
//comboBox2.ValueMember = "items";
comboBox2.DataSource = myDataset.Tables["saving1"];
comboBox2.DisplayMember = "items";
comboBox2.ValueMember = "ID";
quantitys.DataBindings.Add("Text", myDataset, "saving1.quantity");*********
receipts.DataBindings.Add("Text", myDataset, "saving1.receipt");***********
cashs.DataBindings.Add("Text", myDataset, "saving1.cash");**********
cheques.DataBindings.Add("Text", myDataset, "saving1.cheque");********
Try commenting out the line:
// dataGridView2.DataMember = "saving1";
line since you already set the DataSource to a specific DataTable in the DataSet
I created a view named "FamilyView" to join 2 tables(Families and SStatus) and replace an id in the first table(Families) by its name existing in the second table(SStatus) (the column is now called "Status")
This view is now displayed in a datagridview that the user can modify
Sda = new SqlDataAdapter("Select * from FamilyView",con);
Sda.Fill(ds);
dg.DataSource = ds.Tables[0];
dg.Refresh();
What i want is to transform the column cells "Status" to comboboxes containing all Names from SStatus
SqlDataAdapter sadapter = new SqlDataAdapter("Select * From SStatus", con);
DataSet ds1 = new DataSet();
sadapter.Fill(ds1);
i found this code:
DataGridViewComboBoxCell ComboColumn = (DataGridViewComboBoxCell)(dg.Rows[i].Cells[0]);
ComboColumn.DataSource = ds1.Tables[0];
ComboColumn.DisplayMember = "Name";
but i can't replace the cell
and this code but I'm not sure how to use it:
Adding bound combobox to datagridview
BindingSource StatusBD = new BindingSource();
StatusBD.DataSource = ds1;
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
colType.HeaderText = "Status";
colType.DropDownWidth = 90;
colType.Width = 90;
//colType.DataPropertyName = "Name";
colType.DataSource = ds;
colType.DisplayMember = "Name";
colType.ValueMember = "IdStatus";
dg.Columns.Insert(dg.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType);
Your data source is empty: it should contain 2 tables: one with the SStatus and one with Families.
and then follow my as in your post:
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
BindingSource wizardBindingSource = new BindingSource();
wizardBindingSource.DataSource = dataSet;
wizardBindingSource.DataMember = "protocol"; // This is the table in the set
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataPropertyName = "wizardProtocol";
colType.DataSource = wizardBindingSource;
colType.DisplayMember = "protocolName";
colType.ValueMember = "idprotocols"
Here idProtocol (which is referenced as protocol in the "pcap" table) is mapped to protocolName.