Number of comboboxes increase after the first set of results - c#

I am populating my datagrid based on a value in the textbox.
One of the field values in my grid view is a combobox.On a particular text box entry it shows me the correct results but wen I give another value in the text box, the combobox increases its number which means If I enter 100, the data is populated correctly in my combobox but for any value that is provided next the number of combobox becomes 2.I don't know why this happens. This is the code on button click. please help
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "Supplier";
//execute sql data adapter to get supplier values
DataTable dt = obj.SqlDataTable("select name1 from blahblah");
//foreach (DataRow supplier in dt.DataSet.Tables[0].Rows)
//{
// combo.Items.Add(supplier[0]);
//}
//dataGridView1.Columns.Add(combo);
foreach (DataRow row in dt.Rows)
{
combo.Items.Add(row["NAME1"].ToString());
}
dataGridView1.Columns.Add(combo);

You're adding a new combobox on every click... instead check if the comboboxColumn is already added and appropriately modify its contents if it is already present.
To do this check, name your combobox column like this:
combo.Name = "Supplier";
the name property will not show in the UI, but Windows Forms will remember it. Then, you can test if your column is already added with:
if (!dataGridView1.Columns.Contains("Supplier"))

I'm not sure about the textbox, but everytime you click, a new DataGridViewComboBoxColumn is added to the grid. If you click 5 times, you'll see 5 DataGridViewComboBoxColumns with the dropdown being the result of the sql query.
You would need to check if the DataGridViewComboBoxColumns combo was already added:
if (dataGridView1.Columns.IndexOf(combo) < 0)
{
// Add
}

Related

How can I get DataGridView combobox cell value to be written in the MessageBox in C#?

I want to read the the combobox column as shown in the picture, i've tried using
string mode = dt.Rows[0]["Mode"].ToString();
But it doesn't work, it read the USID column instead.
How to read the combobox value?
datatable
private void getmode()
{
//from here
var modelist = new List<string>() { "Reg0", "Basic", "Extended" };
dgvmode.DataSource = modelist;
dgvmode.HeaderText = "Mode";
dtDataGridView.Columns.Add(dgvmode);
// until here, i've create a combobox column in my datatable
string mode = dt.Rows[i]["Mode"].ToString(); // this line got error, it can't read the "Mode" column and say it is not exist, but in my picture, it is exist as a combobox column.
Messagebox.Show(mode); // here to show i get the combobox value
}
datatable is unable to reada datagridview feature, thus, when i using
yourdatatable.Rows[i]["Mode"].ToString();
it will comes out an error (something likie "Mode" column doesnt exist)
even you change the "Mode" to an integer that indicate the column you want to read, it will automatically read the column that create by datatable only. For example :
yourdatatable.Rows[i][0].ToString();
it wont read the combobox column and it will read normal column instead (will not read combobox column ("Mode"), which is the first column. But it will read the column ("USID"), which is the second column).
then, i need to use datagridview like the code below to read the combobox value:
yourDataGridView.Rows[i].Cells[0].Value.ToString()

How to clear data grid view rows and columns except the column headers

I have a quantity based information data grid view it has 3 columns of type text and 1 column of type check box, now this data grid view is filled with different item quantities and different expire dates for the same item from the inventory table whenever the user enters an item name.
The problem is whenever the item is selected and inserted in another data grid view using a button named as Add Item the tools used for data entry are cleared also the data grid view of quantity based information should be cleared, I tried this code but it erases the data grid view completely I just want the data retrieved from database only to be cleared and the headers of the data grid view still appear.
This codes are used in Add Item button
DataRow r = dt.NewRow();
r[0] = sBillItemBartxt.Text;
r[1] = sBillItemNametxt.Text;
r[2] = itemQuanttxt.Text;
r[3] = itemPricetxt.Text;
r[4] = itemTtlPricetxt.Text;
r[5] = expire;
dt.Rows.Add(r);
sBilldgv.DataSource = dt;
clearItemsText();
sBillTtlCostlbl.Text = (from DataGridViewRow row in sBilldgv.Rows where row.Cells[4].FormattedValue.ToString() != string.Empty select Convert.ToDouble(row.Cells[4].FormattedValue)).Sum().ToString();
sBillItemBartxt.ReadOnly = sBillItemNametxt.ReadOnly = false;
dtRes.Clear();
exDatedgv.DataSource = null;
exDatedgv.Rows.Clear();
exDatedgv.Columns.Clear();
They can be cleared nearly the same way as you add them (Without removing columns).
MyDataGridView.Rows.Clear();
This will target rows instead of columns.
I think your header is being cleared because of
exDatedgv.Columns.Clear();
Also if you only wish to remove the rows that are repeated, you might want to consider using a loop to check for the repeated row and remove that row only before adding a new one.
I would also tell you to use a BindingList with your datagridview but since one of your columns is a checkbox im not really sure how you could achieve this with a BindingList
It is unclear from your code what you are trying to do. Since you are using as DataTable I am not sure why the DataTable dtRes.Clear(); does not work as this will clear all the data and KEEP the column headers. When you set exDatedgv.DataSource = null; this will clear the rows and columns so the next two lines are superfluous. To get the DataGridView to clear as you describe… simply Clear the DataTable associated with that DataGridView. This will leave the headers intact, however after this "Clear" there will be no data in the table, so if you try to re-bind the table you just cleared, obviously it will be empty. If you do not want to remove the data from the table, then you will have to either set the headers yourself, create an empty table for this purpose or simply (not the best solution) create a copy from a master. Below I made a data bound DataGridView, then cleared it as described above with button 2, then re-set (re-bind) the DataGridView to a copy of the original table. This clears the DataGridView leaving the headers when pressing button 2, then re-sets the DataGridView to the original data when pressing button 3. Hope this helps.
private void button2_Click(object sender, EventArgs e) {
//dataGridView1.Columns.Clear(); <-- clears headers
//dataGridView1.Rows.Clear(); <-- will crash if data is bound
//dataGridView1.DataSource = null; <-- removes headers
dt.Clear(); // <-- Clears data and leaves headers, removes data from table!
}
private void button3_Click(object sender, EventArgs e) {
dt = masterTable.Copy(); // <-- Get a new table if it was cleared
dataGridView1.DataSource = dt;
}

Using custom CheckBoxComboBox in DataGridView column

I need to use the combobox control with items that can be checked in the DataGridView column. So i have found one control from the following link
https://github.com/sgissinger/CheckBoxComboBox/
In this the basic CheckBoxComboBox is working fine in the demo and it has extended DataGridViewCheckBoxComboBoxColumn class that can be used in DataGridView for a single column.
Now on adding this column in DataGridView on design time, with DataGrid enabled to add new rows, when a data is inserted in another column and value is selected from this column, the ParseFormattedValue() is giving null exception.
Also when adding a new row using code, then GetFormattedValue() is giving null exception in value parameter of it.
In DataGridView I have added two columns, one is simple textbox column and another is DataGridViewCheckBoxComboBoxColumn adding week day names in it.
Now when I try to add a new row by
dataGridView1.Rows.Add();
its showing exception in GetFormattedValue() as null is coming in value parameter of it.
The use of custom CheckBoxComboBox control in DataGridView is done. First I have added a DataGridViewTextBoxColumn or any other as per your requirement and then add the custom CheckBoxComboBox column in that DataGridView in following way.
First you need to create the list of items to be shown in that Combo Box
List<Status> statuses = new List<Status>();
statuses.Add(new Status(1, "Sunday"));
statuses.Add(new Status(2, "Monday"));
statuses.Add(new Status(3, "Tuesday"));
statuses.Add(new Status(4, "Wednesday"));
statuses.Add(new Status(5, "Thursday"));
statuses.Add(new Status(6, "Friday"));
statuses.Add(new Status(7, "Saturday"));
Then you need to create the object of DataGridViewCheckBoxComboBoxColumn
DataGridViewCheckBoxComboBoxColumn comboboxColumn = new DataGridViewCheckBoxComboBoxColumn();
Create an object of ListSelectionWrapper from that statuses List object and set its TextSeparator property.
ListSelectionWrapper<Object> wrappedList = new ListSelectionWrapper<Object>(statuses);
wrappedList.TextSeparator = comboboxColumn.TextSeparator;
Add comboboxColumn other properties as
comboboxColumn.DataSource = wrappedList;
comboboxColumn.ValueMember = "Selected";
comboboxColumn.DisplayMemberSingleItem = "Name";
comboboxColumn.DisplayMember = "NameConcatenated";
And then insert the column in DataGridView
dgvKioskList.Columns.Add(comboboxColumn);
After this your column is inserted in your DataGridView. Now to insert a new row with pre-selected some list items, you need to create a Dictionary object like
Dictionary<String, Object> objSelectedDays = new Dictionary<String, Object>();
If you want to select the Sunday and Tuesday from the ComboBox for example you could write
objSelectedDays.Add("Sunday", statuses[0]);
objSelectedDays.Add("Tuesday", statuses[2]);
After this when you insert a new row into DataGridView with your other data and this objSelectedDays object, the new row will be added to grid
datagridView1.Rows.Add("ID1", objSelectedDays);
where "ID1" is inserted into simple DataGridViewTextBoxColumn
If you want to read the selected values from the datagrid then type cast the cell into Dictionary object like
var values = datagridView1.Rows[0].Cells[1].Value as Dictionary<String, Object>;
and then loop though the values object array to read the selected values from the particular rows CheckBoxComboBox control

Set Combo Box in Datagridview Column

I have a DataGridView (dgvTable) with 2 columns. The first column contains combo boxes with preset data from a database. The second column is just text.
I am trying to set the selection of the combo boxes in the first column based on the information in the second.
I simplified my code a bit to what I need help with:
string data = "MATCH THIS VARIABLE";
foreach (DataGridViewRow row in dgvTable.Rows)
{
if (match.Equals(row.Cells[1].Value.ToString())) //checking to see if the second column value matches data
{
row.Cells[0].Value = "HELP"; //if the second column value == data then set the combobox selected value to "HELP"
}
}
The combo boxes doesn't show the value
EDIT:
I started a new project and made a datagridview and added a columncombobox. I did set the value of the combobox successfully. The only difference is I am trying to change the datagridview combobox value in a separate window. Would that change anything?
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlName");
ddl.SelectedValue = "HELP";

How to get Column Value of a DataRow in a Datatable

I have a DataTable which is bind to dataGridview in my code.
When I get datas from database, the gridview works fine. it fills with data.
What I want to do is getting the primary key value of the specified row.
Ex:
PK Address Phone
1 xxxyyyzzz... 1234567
2 aaabbbccc... 2345678
What I want is this. User will click on any row, then click on a button to add some stuff.
Then I will get PK value, and do other stuffs.
How can I do it?
Hmm can you specify how and when you are talking about getting this value?
You can do this:
int index = dt.Rows.IndexOf(row);
But I am not sure what the point of that would be, if you already have the specified row, why can't you just get the PK via row[columnName]?
But this is more resource intensive than just looping through with a for loop.
Do you need this before or after binding to the dataGridView? If you need to get the value from the dataGridView row that is different.
For your edit:
You would can get the selected row like so:
if (yourDataViewGrid.SelectedRows.Count == 1)
{
Int pk = yourDataViewGrid.Rows[yourDataViewGrid.SelectedRows[0].Index].Cells["PK"].Value.ToString();
}
If you are doing it by some other method like using a checkbox to select a row, you would do this:
foreach (DataGridViewRow row in YourDataGridView.Rows)
{
if ((Boolean)((DataGridViewCheckBoxCell)row.Cells["CheckBoxName"]).FormattedValue)
{
Int pk = rows.Cells["PK"].Value.ToString();
}
}
The DataGridView control binds to a DataTable using the DataView class. You can use something like this to get the DataRow of a DataGridViewRow
var vrow = (DataRowView)grid.Rows[12].DataBoundItem; // get the bound object
var drow = vrow.Row; // the Row property references the real DataRow
where 12 is the index you are looking for. Sometimes it helps to set the DataSource property to a DataView explicitly and keep a reference to it on your form. The view will know the sorting of the data too
var view = new DataView(table);
grid.DataSource = view;

Categories