Adding bound combobox to datagridview - c#
The scenario is almost the same as http://arsalantamiz.blogspot.com/2008/09/binding-datagridview-combobox-column.html. but I can't get it working on c#...
I have mySql db with two tables:
1. protocols
2. pcapdata
In protocols tables I have a two fields: idprotocols and protocolName
Int the pcaps table I have wizardProtocol (which is "linked" to the idprotocols field)
What I'm trying to get is to have a combobox containing names which will replace the wizardprotocol field. Next, If the user updates the "names" combobox the wizardProtocol will be changed accordingly (so I will be able to update the changes in the database accordingly).
Now, after reading some information on the net: I've written the following code:
public void Bind(ref DataGridView dataGridView)
{
try
{
mySqlDataAdapter = new MySqlDataAdapter(SELECT_ALL_PCAP, _con);
mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand();
mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand();
mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand();
dataSet = new DataSet();
mySqlDataAdapter.Fill(dataSet, "pcap");
MySqlDataAdapter adp2 = new MySqlDataAdapter(SELECT_ALL_PROTOCOL, _con);
MySqlCommandBuilder builder = new MySqlCommandBuilder(adp2);
adp2.UpdateCommand = builder.GetUpdateCommand();
adp2.DeleteCommand = builder.GetDeleteCommand();
adp2.InsertCommand = builder.GetInsertCommand();
adp2.Fill(dataSet, "protocol");
bindingSource = new BindingSource();
bindingSource.DataSource = dataSet;
bindingSource.DataMember = "pcap";
dataGridView.DataSource = bindingSource;
dataGridView.Columns["length"].ReadOnly = true;
dataGridView.Columns["length"].DefaultCellStyle.ForeColor = System.Drawing.Color.SandyBrown;
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataPropertyName = "wizardProtocol";
colType.DataSource = bindingSource;
colType.DisplayMember = "protocolName";
colType.ValueMember = "idprotocols";
dataGridView.Columns.Insert(dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType);
}
catch (System.Exception e)
{
MessageBox.Show(e.ToString());
}
}
I'm trying to manipulable the DisplayMember property, but I fail (I know that the problem is with probably with my data-binding, but I can't figure it out...)
UPDATE: Thanks to the answer, I'm re-attaching the fixed code
mySqlDataAdapter = new MySqlDataAdapter(SELECT_ALL_PCAP, _con);
mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand();
mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand();
mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand();
dataSet = new DataSet();
mySqlDataAdapter.Fill(dataSet, "pcap");
MySqlDataAdapter adp2 = new MySqlDataAdapter(SELECT_ALL_PROTOCOL, _con);
MySqlCommandBuilder builder = new MySqlCommandBuilder(adp2);
adp2.UpdateCommand = builder.GetUpdateCommand();
adp2.DeleteCommand = builder.GetDeleteCommand();
adp2.InsertCommand = builder.GetInsertCommand();
adp2.Fill(dataSet, "protocol");
bindingSource = new BindingSource();
bindingSource.DataSource = dataSet;
bindingSource.DataMember = "pcap";
dataGridView.DataSource = bindingSource;
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
BindingSource wizardBindingSource = new BindingSource();
wizardBindingSource.DataSource = dataSet;
wizardBindingSource.DataMember = "protocol";
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataPropertyName = "wizardProtocol";
colType.DataSource = wizardBindingSource;
colType.DisplayMember = "protocolName";
colType.ValueMember = "idprotocols";
dataGridView.Columns.Insert(dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType);
The most obvious thing that you are doing wrong is that you use the same binding source for both your datagridview and for your comboboxcolumn. If you look at the example you provided you'll notice that they create a second bindingsource productBindingSource.
So what you need to do is create a bindingsource (let's call it wizardProtocolBindingSource) which you then fill with the data from your protocols table. This becomes the datasource for your combobox column.
The key code looks something like this:
// You bind the datagridview just as before
// this dataset should have the idprotocols field which is your foreign key
// to the protocols table - you will probably want this to be hidden.
bindingSource = new BindingSource();
bindingSource.DataSource = dataSet;
bindingSource.DataMember = "pcap";
dataGridView.DataSource = bindingSource;
// hide the foreign key column
dataGridView.Columns["idProtocols"].Visible = false;
// here we populate your comboboxcolumn binding source
wizardProtocolBindingSource= new BindingSource();
// this dataset is from the protocols table
wizardProtocolBindingSource.DataSource = dataSet;
// Add the combobox column
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataSource = wizardProtocolBindingSource;
// The DataPropertyName refers to the foreign key column on the datagridview datasource
colType.DataPropertyName = "wizardProtocol";
// The display member is the name column in the column datasource
colType.DisplayMember = "protocolName";
// The value member is the primary key of the protols table
colType.ValueMember = "idprotocols";
// I usually just add the column but you can insert if you need a particular position
dataGridView.Columns.Add(colType);
The above should work for you, though not knowing the names of your dataset columns I had to guess a little.
Related
New columns added to datatable are not showing up in datagridview
I have created a datatable then manually added two new columns in position 0 and 1, and given them default values. When I loop through the datatable it prints all the values out correctly and everything seems to be there. but when I pass the datatable to a DataGridView via a binding source it doesn't show the two new columns in the datagridview. Any idea as to what im doing wrong? Regards Amarino DataTable lDT2 = Conn.ExecuteStoredProcedureValidation(lDT); DataColumn newColumn1 = new DataColumn("TestName", typeof(string)); DataColumn newColumn2 = new DataColumn("SheetName", typeof(string)); newColumn1.DefaultValue = "test"; newColumn2.DefaultValue = "test2"; lDT2.Columns.Add(newColumn2); lDT2.Columns.Add(newColumn1); lDT2.Columns["TestName"].SetOrdinal(0); lDT2.Columns["SheetName"].SetOrdinal(1); DataGridView lDGV = new DataGridView(); lDGV.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing; lDGV.RowHeadersVisible = false; BindingSource BindingSource1 = new BindingSource(); //create new data binding source BindingSource1.DataSource = lDT2; //SetData source change to LDT2 lDGV.DataSource = BindingSource1; lDGV.RowHeadersVisible = true; lDGV.Tag = page.Controls[0].Tag; lDGV.AccessibleName = page.Controls[0].AccessibleName; lFormV.tabControl_Val.TabPages[page.Name].Show(); lFormV.tabControl_Val.TabPages[page.Name].Controls.Add(lDGV);
Bind Specific Columns of Datatable to Datagridview in C#
I have a datatable that has many columns, now I have a datagridview that already have columns designed using these codes: frm.RationFeedsdataGridView.ColumnCount = 4; frm.RationFeedsdataGridView.Columns[1].HeaderText = "Number"; frm.RationFeedsdataGridView.Columns[1].HeaderText = "Name"; frm.RationFeedsdataGridView.Columns[2].HeaderText = "Quantity"; frm.RationFeedsdataGridView.Columns[3].HeaderText = "Percent"; Now I want to bind specific columns of my datatable to these columns of datagridview somthing like that; frm.RationFeedsdataGridView.Columns["Name"].DataPropertyName = "FeedName"; that FeedName is header of a column in datatable what should I do?
this is how I fixed my problem: frm.RationFeedsdataGridView.AutoGenerateColumns = false; frm.RationFeedsdataGridView.Columns[1].Name = "Name"; frm.RationFeedsdataGridView.Columns[1].HeaderText = "Name"; frm.RationFeedsdataGridView.Columns[1].DataPropertyName = "FeedName"; frm.RationFeedsdataGridView.Columns[2].Name = "Quantity"; frm.RationFeedsdataGridView.Columns[2].HeaderText = "Quantity"; frm.RationFeedsdataGridView.Columns[2].DataPropertyName = "Quantity"; frm.RationFeedsdataGridView.Columns[3].Name = "Percent"; frm.RationFeedsdataGridView.Columns[3].HeaderText = "Percent"; frm.RationFeedsdataGridView.Columns[3].DataPropertyName = "Percent"; frm.RationFeedsdataGridView.DataSource = DTable;
Cannot add rows to my data-bound dataGridview dynamically
RDP0 yeni = new RDP0(); yeni.IPADDRESS = "1.1.1.1"; yeni.PASSWORD = " 10akh0"; yeni.NO = 8; yeni.CUSTID = 1000; testList.Add(yeni); dataGridView1.DataSource = testList; I'm getting data-bound error therefore I cannot add rows. Any help would be great. This is how I bound data to my dataGV: tm = new testModel(); var query = from fe in tm.ERDP0 select fe; testList = query.ToList(); dataGridView1.DataSource = testList;
If the DataGridView is data bound you cannot add new rows/columns to the DataGridView directly. But you could add a row to a DataTable which will update your DataGridView automatically. DataTable dt = dataGridView1.DataSource as DataTable; dt.Rows.Add("new row"); Or you could add the new row to your source list and then reset the DataSource: testList.Add(youritem); dataGridView1.DataSource = null; dataGridView1.DataSource = testList;
How to fill DataGridViewComboBoxColumn from a database table column without using datareader
Here is my code: SqlDataAdapter GridDataAdapter = new SqlDataAdapter(query, con); DataSet GridDataSet = new DataSet(); GridDataAdapter.Fill(GridDataSet, tbln); dataGridView1.DataSource = GridDataSet; DataGridViewComboBoxColumn dgvCB = new DataGridViewComboBoxColumn(); dataGridView1.DataMember = tbln; Here, I want to fetch data for DataGridViewComboBox from a database table column. How can I fill the DataGridViewComboBoxColumn without using a DataReader?
You already have the dataset filled, you could just iterate over the row collection if it contains the values that you want the DGVCombo to contain. So, the most straightforward way would be something along the lines of: foreach(DataRow r in GridDataSet.Tables[0].Rows) { dgvCB.Items.Add(r["MyColumn"]); } Where .Tables[0] has the column("MyColumn") that you are looking for...
This should be what you need... DataGridViewComboBoxColumn dgvCB = new DataGridViewComboBoxColumn(); dgvCB.Name = "lastname"; dgvCB.DataSource = tbln; dgvCB.HeaderText = "Last"; //uncomment this to actually select the value in the combo box //dgvCB.DataPropertyName = "lastname"; dgvCB.ValueMember = "lastname"; dataGridView1.Columns.Add(dgvCB);
how to bind datatable to datagridview in c#
I need to bind my DataTable to my DataGridView. i do this: DTable = new DataTable(); SBind = new BindingSource(); //ServersTable - DataGridView for (int i = 0; i < ServersTable.ColumnCount; ++i) { DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name)); } for (int i = 0; i < Apps.Count; ++i) { DataRow r = DTable.NewRow(); r.BeginEdit(); foreach (DataColumn c in DTable.Columns) { r[c.ColumnName] = //writing values } r.EndEdit(); DTable.Rows.Add(r); } SBind.DataSource = DTable; ServersTable.DataSource = SBind; But all i got is DataTable ADDS NEW columns to my DataGridView. I don't need this, i just need to write under existing columns.
Try this: ServersTable.Columns.Clear(); ServersTable.DataSource = SBind; If you don't want to clear all the existing columns, you have to set DataPropertyName for each existing column like this: for (int i = 0; i < ServersTable.ColumnCount; ++i) { DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name)); ServersTable.Columns[i].DataPropertyName = ServersTable.Columns[i].Name; }
Even better: DataTable DTable = new DataTable(); BindingSource SBind = new BindingSource(); SBind.DataSource = DTable; DataGridView ServersTable = new DataGridView(); ServersTable.AutoGenerateColumns = false; ServersTable.DataSource = DTable; ServersTable.DataSource = SBind; ServersTable.Refresh(); You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.
On the DataGridView, set the DataPropertyName of the columns to your column names of your DataTable.
// I built my datatable first, and populated it, columns, rows and all. //Then, once the datatable is functional, do the following to bind it to the DGV. NOTE: the DGV's AutoGenerateColumns property must be 'true' for this example, or the "assigning" of column names from datatable to dgv will not work. I also "added" my datatable to a dataset previously, but I don't think that is necessary. BindingSource SBind = new BindingSource(); SBind.DataSource = dtSourceData; ADGView1.AutoGenerateColumns = true; //must be "true" here ADGView1.Columns.Clear(); ADGView1.DataSource = SBind; //set DGV's column names and headings from the Datatable properties for (int i = 0; i < ADGView1.Columns.Count; i++) { ADGView1.Columns[i].DataPropertyName = dtSourceData.Columns[i].ColumnName; ADGView1.Columns[i].HeaderText = dtSourceData.Columns[i].Caption; } ADGView1.Enabled = true; ADGView1.Refresh();
foreach (DictionaryEntry entry in Hashtable) { datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString()); }
private void Form1_Load(object sender, EventArgs e) { DataTable StudentDataTable = new DataTable("Student"); //perform this on the Load Event of the form private void AddColumns() { StudentDataTable.Columns.Add("First_Int_Column", typeof(int)); StudentDataTable.Columns.Add("Second_String_Column", typeof(String)); this.dataGridViewDisplay.DataSource = StudentDataTable; } } //Save_Button_Event to save the form field to the table which is then bind to the TableGridView private void SaveForm() { StudentDataTable.Rows.Add(new object[] { textBoxFirst.Text, textBoxSecond.Text}); dataGridViewDisplay.DataSource = StudentDataTable; }
for example we want to set a DataTable 'Users' to DataGridView by followig 2 steps : step 1 - get all Users by : public DataTable getAllUsers() { OracleConnection Connection = new OracleConnection(stringConnection); Connection.ConnectionString = stringConnection; Connection.Open(); DataSet dataSet = new DataSet(); OracleCommand cmd = new OracleCommand("semect * from Users"); cmd.CommandType = CommandType.Text; cmd.Connection = Connection; using (OracleDataAdapter dataAdapter = new OracleDataAdapter()) { dataAdapter.SelectCommand = cmd; dataAdapter.Fill(dataSet); } return dataSet.Tables[0]; } step 2- set the return result to DataGridView : public void setTableToDgv(DataGridView DGV, DataTable table) { DGV.DataSource = table; } using example: setTableToDgv(dgv_client,getAllUsers());