DataGridViewComboBoxColumn get value from other column - c#

I pull the data from sql database and fill datagridView1 with it:
dataGridView1.DataSource = bsour;
User will be able to edit value in 1 column, but possible values for that column are only Null, 0, 1 or 2 so to prevent from inputting incorrect value i decided to do a ComboBoxColumn:
DataGridViewComboBoxColumn col1 = new DataGridViewComboBoxColumn();
col1.Name = "il_normal_combo";
col1.HeaderText = "Normal";
col1.Items.Add("");
col1.Items.Add("0");
col1.Items.Add("1");
col1.Items.Add("2");
dataGridView1.Columns.Insert(5, col1);
The other now unnecessary column I'll hide with .Visible = false;
I want the ComboBoxColumn to display database values from that other column that will be hidden and i can't seem to get it to work.
What i have tried:
col1.ValueMember = "il_normal";
col1.DisplayMember = "il_normal";
Those don't work but without error message.
This doesn't work and produces error "Values are incorrect"
for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
dataGridView1.Rows[i].Cells[5].Value = dataGridView1.Rows[i].Cells[7].Value;
}

I found similar question here
Change DataGridViewColumn to DataGridViewComboBoxColumn in bound DataGridView
but solution in that post didn't work for me. In ComboBoxColumn instead of number, I got System.Data.DataRows.(something) so i deduced that it doesn't know which column to use (even though there was only one in DataSource) so i added
col1.DisplayMember = "number";
And then it worked :-)

Related

How to delete dynamically created datagridview columns in c#?

Im unable to delete columns that i had created during run time. How do I delete dynamically created columns?
Here is the code to create columns in a button :
//creating new column
DataGridViewTextBoxColumn column1 = new DataGridViewTextBoxColumn();
column1.ReadOnly = false;
column1.Name = "column"+ incrementcount;
column1.Resizable = DataGridViewTriState.True;
//column1.SortMode = DataGridViewColumnSortMode.Automatic;
column1.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
column1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
column1.HeaderText = "Column" + incrementcount;
column1.Width = 100;
dataGridView4.AutoGenerateColumns = false;
dataGridView4.Columns.Add(column1);
And im trying to delete the column like this, I also tried to hide the column :
// dataGridView4.Columns[poss].Visible = false;
dataGridView4.Columns.Remove(dataGridView4.Columns[positionindex].HeaderText);
dataGridView4.Refresh();
But still the columns are visible. How do I delete it?
I would suggest to use:
Visibility flag to disable the column
Use the DataGridView.Columns.RemoveAt(YourIndex)
To get the index of a column use:
DataGridView.Columns["YourColumn"].Index;

Manually added column not showing in windows form DataGridView

I have a DataGridView (CurrentLine) with a DataSet source table. I have added a combobox column with a different datasource, which works fine. The I tried adding another column, but the DataGridView refuses to show it!
I have tried adding a regular column via DataGridViewColumn and via DataGridViewTextBoxColumn (as I basically need a regular column with nothing but numbers).
I tried setting the visibility property to true.
Nothing seems to work and I have no idea why.
da1.Fill(Orders, Order);
da2.Fill(Orders, Lines);
da3.Fill(Orders, Products);
CurrentLine.DataSource = Orders.Tables[Lines];
CurrentLine.Columns["fkPrdctnum"].Visible = false;
CurrentLine.Columns["linenum"].Width = 60;
CurrentLine.Columns["linenum"].HeaderText = "Number";
CurrentLine.Columns["linenum"].ReadOnly = true;
CurrentLine.Columns["lineQuantity"].HeaderText = "Quantity";
CurrentLine.Columns["lineQuantity"].Width = 70;
CurrentLine.Columns["linePrdctPrice"].HeaderText = "Unit Price";
CurrentLine.Columns["linePrdctPrice"].Width = 100;
DataGridViewComboBoxColumn prod = new DataGridViewComboBoxColumn();
prod.DataSource = Orders.Tables[Products];
prod.DisplayMember = "prdctName";
prod.ValueMember = "prdctNum";
prod.HeaderText = "Product";
CurrentLine.Columns.Add(prod);
for (int i=0; i<CurrentLine.Rows.Count; i++)
{
int product = Convert.ToInt32(Orders.Tables[Lines].Rows[i][1]); //This loop sets the values of the combobox according to the order lines in the orderline table in the dataset.
CurrentLine.Rows[i].Cells[4].Value = product;
}
DataGridViewColumn LinePrice = new DataGridViewColumn();
LinePrice.HeaderText = "Line Price";
LinePrice.Width = 100;
LinePrice.ReadOnly = true;
CurrentLine.Columns.Add(LinePrice);
Just to be clear: the combobox works fine, and the loop to set its values also works fine. The problem seems to be somewhere with the DataGridViewColumn LinePrice.
Any idea what's going on? Why does one type of column (combobox) works fine but the other does not?
p.s. I have cut lines of code regarding another DataGridView which fills with the Order table, as that one works fine and is irrelevant to the problem so far as I can tell).
UPDATE: When I move the box to before the combobox column, it suddenly appears... Not sure why though, and it's not where I want it to be in the DataGridView.
Change your code as :
DataTable Orders = Orders.Tables[Lines];
CurrentLine.DataSource = Orders;
for (int i = 0; i < CurrentLine.Rows.Count-1; i++)
{
string product =Orders.Rows[i][1].ToString (); //This loop sets the values of the combobox according to the order lines in the orderline table in the dataset.
CurrentLine.Rows[i].Cells[4].Value = product;
}
DataColumn LinePrice = new DataColumn("Line Price");
Orders.Columns.Add(LinePrice);
It should be works
I made use of your code and I encountered the below error during the execution of code fragment which adds "Line Price" column.
Column cannot be added because its CellType property is null.
The above error can be generated if columns are added after you have already added rows into the DataGridView since it is not possible determine the cell type.
I managed to display the column based on the order you requested using the below code fragment. Please try to add in the new line and confirm if this helps to resolve your issue.
DataGridViewColumn LinePrice = new DataGridViewColumn();
LinePrice.HeaderText = "Line Price";
LinePrice.Width = 100;
LinePrice.ReadOnly = true;
LinePrice.CellTemplate = new DataGridViewTextBoxCell(); // Define the cell type of the new column
CurrentLine.Columns.Add(LinePrice);
NOTE: The for loop can generate error (#o_weisman also mentioned this) while making use of i to get hold of the Orders.Rows[i] row. Further, it seems that you have a master try catch block which is suppressing the errors. Please review your code to ensure that you have implemented error traps accordingly.

Add new column at specified position programmatically in C# Datagridview

I have a datagridview with 5(0-5) columns. All the rows value I retrieve from the hashtable created.
Now I've set a condition that state if column 4 contain empty value from hashtable then add new column next to column 4 which makes the new added column index at position 5 and the value of hashtable previously for column 5 change to column 7.
I do the code like this:
int number = dataGridView1.Rows.Add();
dataGridView1.Rows[number].Cells[0].Value = result; //id
dataGridView1.Rows[number].Cells[1].Value = newAddress; //ip
dataGridView1.Rows[number].Cells[2].Value = (string)((Hashtable)ht[1])["value"]; //name
dataGridView1.Rows[number].Cells[3].Value = (string)((Hashtable)ht[2])["value"]; //description
if (!ht.ContainsValue(3))
{
// Create a Save button column
DataGridViewImageButtonSaveColumn columnSave = new DataGridViewImageButtonSaveColumn();
// Set column values
columnSave.Name = "SaveButton";
columnSave.HeaderText = "";
//Add the columns to the grid
dataGridView1.Rows[number].Cells[4].ReadOnly = false;
dataGridView1.Columns[5].Add(columnSave); //im not sure about this codes
dataGridView1.Rows[number].Cells[6].Value = (string)((Hashtable)ht[4])["value"]; //count
}
else
{
dataGridView1.Rows[number].Cells[4].Value = (string)((Hashtable)ht[3])["value"]; //location
dataGridView1.Rows[number].Cells[5].Value = (string)((Hashtable)ht[4])["value"]; //count
}
However, i'm not sure if I do this right because I receive error at the line commented
dataGridView1.Columns[5].Add(columnSave); //im not sure about this codes
Seems like this code is wrong. Can anyone please advise?
Try dataGridView1.Columns.Insert(5, columnSave); instead.
MSDN reference: DataGridViewColumnCollection.Insert Method
A simple way to insert a checkbox to certain column of Data grid:
DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
dataGridView1.Columns.Insert(**certain column number**, chk);
for example if you want to add checkbox to column 1 you mus type
dataGridView1.Columns.Insert(0, chk);

How to get Display Member of All Combobox columns in dataGridView in C#?

I'm Working on a windows form GUI that has a dataGridView. In dataGridView I've two columns. The first Column Type is a ComboBoxColumn for Insurance id and name and second one is Text box for insurance code number.
ComboBox Column's Datasource is already set and works.
here is code on form load :
DataGridViewComboBoxColumn Cb = new DataGridViewComboBoxColumn();
DataTable dt = new DataTable();
dt = _clsT.Fill_In_DataTable("SELECT insuranceId, insuranceName FROM insurance", false);
Cb.DataSource = dt;
Cb.Name = "insurance";
Cb.DisplayMember = "insuranceName";
Cb.ValueMember = "insuranceId";
dgv.Columns.Insert(0, Cb);
dgv.Refresh();
after loading form i can fill dgv(DataGridView) Rows From combobox items and at last i want get all row's information with clicking on a button.
here is my code for getting rows data on btn click event
if (dgv.Rows.Count > 0)
{
for (int i = 0; i < dgv.Rows.Count; i++)
{
lst1.Items.Add(dgv.Rows[i].Cells[0].Value.ToString());
lst2.Items.Add(dgv.Rows[i].Cells[1].Value.ToString());
//lst3.Items.Add(dgv.Rows.Cell[0] get displayMember.ToString() ) //what i must to do?
}
}
ok from here i can get insuranceId and insuranceCodeNumber but how to get displayMembers ?
please help me ... thanks
try this
dgv.Rows[i].Cells[0].FormattedValue.ToString();
dgv.Rows[i].Cells[1].FormattedValue.ToString();

C# DataGridView combobox add data programmatically

I have an application with a DataGridView. One of the columns is of the type Combobox. I want to add the items for this combobox programmatically. Here is the code I use for that:
this.dsStatussen = this.statussenMan.getAllStatussen();
DataGridViewComboBoxColumn cd = (DataGridViewComboBoxColumn)this.dgvEenheden.Columns[3];
cd.DataSource = dsStatussen;
cd.DisplayMember = "statussen";
cd.DataPropertyName = "sid";
cd.ValueMember = "status";
Then when I try to add a row I get the following error: "There is no field with the name status". I transelated the error to English because I have a Dutch error.
Here is the code I use for adding the rows:
Eenheden eenhedenMan = new Eenheden(objEvenement.eid);
DataSet EenhedenData = eenhedenMan.getAllEenheden();
foreach (DataRow dr in EenhedenData.Tables[0].Rows)
{
dgvEenheden.Rows.Add(
dr[0].ToString(),
dr[1].ToString(),
dr[2].ToString(),
Convert.ToInt32(dr[6]),
dr[3].ToString(),
dr[4].ToString(),
dr[5].ToString()
);
}
Could someone help me to figure out what I'm doeing wrong? I can't find it. This is the first time I use an DataGridView with comboboxes.
in my experience I found everything seemed to work better if you tied it in through a binding scource, then set the
bindingScource.dataScource.Rows.Add(
dr[0].ToString(),
dr[1].ToString(),
dr[2].ToString(),
Convert.ToInt32(dr[6]),
dr[3].ToString(),
dr[4].ToString(),
dr[5].ToString()
);
Select the correct row? you mean select from the dropdown to see the row inside the datagrid?
int index = dropdown.SelectedIndex();
for(int count = 0; count < dgvEenheden.Rows.Count; count ++)
{
if (dgvEenheden.Rows[count].Cells["<enter col name here>"].Value.ToString().equals(dropdown.Items[index].Text))
{
dgvEenheden.Rows[count].Selected = true; //to select the Row
dgvEenheden.Rows[count].Cells[<Cell Number>].Selected = true; //to select the specific Cell
}
}

Categories