Eliminate changes - c#

When I select an item in the second row, the first row changes and the selected items in the first row changes and copies what I selected in the second row
I just want to ask, how to eliminate these changes?
I don't know if it's because of clearing the items in ComboBox and if I remove the column.Items.Clear() it operates well but I also need to clear the items in the ComboBox
public partial class MultipleEntry : Form
{
DataGridViewComboBoxColumn col1 = new DataGridViewComboBoxColumn();
DataGridViewComboBoxColumn col2 = new DataGridViewComboBoxColumn();
DataGridViewComboBoxColumn col3 = new DataGridViewComboBoxColumn();
DataGridViewTextBoxColumn col4 = new DataGridViewTextBoxColumn();
DataGridViewComboBoxColumn col5 = new DataGridViewComboBoxColumn();
DataGridViewTextBoxColumn col6 = new DataGridViewTextBoxColumn();
DataGridViewComboBoxColumn col7 = new DataGridViewComboBoxColumn();
DataGridViewTextBoxColumn col8 = new DataGridViewTextBoxColumn();
public MultipleEntry()
{
InitializeComponent();
}
private void UNA()
{
string strQuery = "Select TypeName from TYPE where delType='False'";
OleDbDataAdapter adap = new OleDbDataAdapter(strQuery, Program.objConn);
OleDbCommandBuilder build = new OleDbCommandBuilder(adap);
DataTable dt = new DataTable();
adap.Fill(dt);
BindingSource bind = new BindingSource();
bind.DataSource = dt;
//Type
col1.DataPropertyName = "TypeName";
col1.HeaderText = "Type";
col1.Width = 100;
col1.DataSource = bind;
col1.ValueMember = "TypeName";
col1.DisplayMember = "TypeName";
grdMultiple.Columns.Add(col1);
//Category
col2.DataPropertyName = "CategoryName";
col2.HeaderText = "Category";
col2.Width = 100;
grdMultiple.Columns.Add(col2);
//Product Description
col3.DataPropertyName = "ProductDetails";
col3.HeaderText = "Product";
col3.Width = 150;
grdMultiple.Columns.Add(col3);
//Unit
col5.DataPropertyName = "UnitName";
col5.HeaderText = "Unit";
col5.Width = 75;
grdMultiple.Columns.Add(col5);
//Supplier
col7.HeaderText = "Supplier";
col7.Width = 150;
grdMultiple.Columns.Add(col7);
//Quantity
col4.HeaderText = "Qty";
col4.Width = 75;
grdMultiple.Columns.Add(col4);
//Price
col8.HeaderText = "Price";
col8.Width = 75;
grdMultiple.Columns.Add(col8);
//Serial Number
col6.HeaderText = "Serial No";
col6.Width = 80;
grdMultiple.Columns.Add(col6);
}
private void MultipleEntry_Load(object sender, EventArgs e)
{
//try
//{
Program.objConn = new OleDbConnection(Program.Connection);
Program.objConn.Open();
UNA();
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message);
//}
}
string value;
private void grdMultiple_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
int index = grdMultiple.CurrentCell.RowIndex;
if(e.ColumnIndex==0)
{
MessageBox.Show(e.ColumnIndex.ToString() + e.RowIndex.ToString());
object newValue = grdMultiple.CurrentRow.Cells[0].Value;
value = newValue.ToString();
MessageBox.Show(value);
string one = "select c.CategoryName,t.TypeName from CATEGORY c inner join PRODUCT p on p.CategoryNo = c.CategoryNo inner join TYPE t on t.TypeNo=p.TypeNo where t.TypeName='" + value + "'";
OleDbCommand cmdone = new OleDbCommand(one, Program.objConn);
OleDbDataReader rdrOne = cmdone.ExecuteReader();
col2.Items.Clear();
while (rdrOne.Read())
{
col2.Items.Add(rdrOne[0].ToString());
}
}
else if (e.ColumnIndex == 1 && e.RowIndex >=1)
{
MessageBox.Show(e.ColumnIndex.ToString() + e.RowIndex.ToString());
string one = "select c.CategoryName,t.TypeName from CATEGORY c inner join PRODUCT p on p.CategoryNo = c.CategoryNo inner join TYPE t on t.TypeNo=p.TypeNo where t.TypeName='" + value + "'";
OleDbCommand cmdone = new OleDbCommand(one, Program.objConn);
OleDbDataReader rdrOne = cmdone.ExecuteReader();
while (rdrOne.Read())
{
col2.Items.Add(rdrOne[0].ToString());
}
}
else if (e.ColumnIndex == 2 && e.RowIndex >= 1)
{
MessageBox.Show(e.ColumnIndex.ToString() + e.RowIndex.ToString());
col3.Items.Clear();
object newTwo = grdMultiple.CurrentRow.Cells[1].Value;
//MessageBox.Show(newTwo.ToString());
string two = "select p.ProductDetails,c.CategoryName from PRODUCT p inner join Category c on c.CategoryNo = p.CategoryNo where c.CategoryName='" + newTwo.ToString() + "'";
OleDbCommand cmdtwo = new OleDbCommand(two, Program.objConn);
OleDbDataReader rdrtwo = cmdtwo.ExecuteReader();
while (rdrtwo.Read())
{
col3.Items.Add(rdrtwo[0].ToString());
}
}
else if (e.ColumnIndex == 3 && e.RowIndex >= 1)
{
MessageBox.Show(e.ColumnIndex.ToString() + e.RowIndex.ToString());
col5.Items.Clear();
string three = "select u.UnitName from UNIT u";
OleDbCommand cmdThree = new OleDbCommand(three, Program.objConn);
OleDbDataReader rdrThree = cmdThree.ExecuteReader();
while (rdrThree.Read())
{
col5.Items.Add(rdrThree[0].ToString());
}
}
else if (e.ColumnIndex == 4 && e.RowIndex >= 1)
{
MessageBox.Show(e.ColumnIndex.ToString() + e.RowIndex.ToString());
col7.Items.Clear();
string four = "select SupplierCompany from SUPPLIER";
OleDbCommand cmdFour = new OleDbCommand(four, Program.objConn);
OleDbDataReader rdrFour = cmdFour.ExecuteReader();
while (rdrFour.Read())
{
col7.Items.Add(rdrFour[0].ToString());
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

The problem here is that You use DataGridViewComboBoxColumn.Items property improperly. This property is used to access the collection of values for all cells in that column, so whenever You call col2.Items.Clear(), You clear the combo boxes in the whole column. To access value collection for a cell individually, You should do something like this:
//get the cell in selected row in 2nd column
var cell2 = (DataGridViewComboBoxCell)grdMultiple.Rows[index].Cells[2];
//clear the combo box value collection only for this cell
cell2.Items.Clear()
//do the rest accessing the cell's value collection like in the previous line
Hope this solves Your problem.
P.S. You should go back to using e.RowIndex == index in the if statements.

Related

Search a datagridview without doing an sql query

I have two DataGridview's, dgvProducts and dgvCart.
When I transfer a product to from dgvProducts to dgvCart, the specified quantity will deduct from the first datagridview.
But the problem is my textbox search code, it is using a query so the datagridview quantity are reset everytime even when the transaction is not finish.
This is the code for the search of textbox.
private void textOrderSearch_TextChanged(object sender, EventArgs e)
{
if (textOrderSearch.Text != "")
{
crud.FillDataGrid("Select ProductID,BrandName,GenericName,Form,Dosage,Quantity,SellingPrice,D,VE from Products where Status = 'Active' and Quantity > 0 and (ProductID Like '%" + textOrderSearch.Text + "%' or BrandName Like '%" + textOrderSearch.Text + "%' or GenericName Like '%" + textOrderSearch.Text + "%' or Form Like '%" + textOrderSearch.Text + "%' or Dosage Like '%" + textOrderSearch.Text + "%' ) ", ref dgvPOSproduct);
dgvPOSproduct.Columns[0].HeaderText = "ProductID";
dgvPOSproduct.Columns[1].HeaderText = "Brand";
dgvPOSproduct.Columns[2].HeaderText = "Generic";
dgvPOSproduct.Columns[3].HeaderText = "Form";
dgvPOSproduct.Columns[4].HeaderText = "Dosage";
dgvPOSproduct.Columns[5].HeaderText = "Qty";
dgvPOSproduct.Columns[6].HeaderText = "Price";
dgvPOSproduct.Columns[7].HeaderText = "D";
dgvPOSproduct.Columns[8].HeaderText = "VE";
dgvPOSproduct.Columns[0].Width = 65;
dgvPOSproduct.Columns[1].Width = 80;
dgvPOSproduct.Columns[2].Width = 80;
dgvPOSproduct.Columns[3].Width = 58;
dgvPOSproduct.Columns[4].Width = 58;
dgvPOSproduct.Columns[5].Width = 45;
dgvPOSproduct.Columns[6].Width = 55;
dgvPOSproduct.Columns[7].Width = 35;
dgvPOSproduct.Columns[8].Width = 35;
}
else
{
dgvProductSettings();
}
}
And the code for the method of populating the datagridview.
private void dgvProductSettings()
{
crud.FillDataGrid("Select ProductID,BrandName,GenericName,Form,Dosage,Quantity,SellingPrice,D,VE from Products where Status = 'Active' and Quantity > 0", ref dgvPOSproduct);
dgvPOSproduct.Columns[0].HeaderText = "ProductID";
dgvPOSproduct.Columns[1].HeaderText = "Brand";
dgvPOSproduct.Columns[2].HeaderText = "Generic";
dgvPOSproduct.Columns[3].HeaderText = "Form";
dgvPOSproduct.Columns[4].HeaderText = "Dosage";
dgvPOSproduct.Columns[5].HeaderText = "Qty";
dgvPOSproduct.Columns[6].HeaderText = "Price";
dgvPOSproduct.Columns[7].HeaderText = "D";
dgvPOSproduct.Columns[8].HeaderText = "VE";
dgvPOSproduct.Columns[0].Width = 65;
dgvPOSproduct.Columns[1].Width = 80;
dgvPOSproduct.Columns[2].Width = 80;
dgvPOSproduct.Columns[3].Width = 58;
dgvPOSproduct.Columns[4].Width = 58;
dgvPOSproduct.Columns[5].Width = 45;
dgvPOSproduct.Columns[6].Width = 55;
dgvPOSproduct.Columns[7].Width = 35;
dgvPOSproduct.Columns[8].Width = 35;
}
Is there a way to search the datagridview only so it will not need to do a query that is reseting the quantity everytime i do a search? Thank you.
EDIT: added crud method
public crud()
{
cnString = "Data Source=BENJOPC\\SQLEXPRESS;Initial Catalog=MARISCHELLdatabase;Integrated Security=True";
cn = new SqlConnection(cnString);
}
public void FillDataGrid(string sql, ref ns1.BunifuCustomDataGrid dg)
{
try
{
DataSet ds = new DataSet();
cn.Open();
cmd = new SqlCommand(sql, cn);
adptr = new SqlDataAdapter(cmd);
adptr.Fill(ds);
dg.DataSource = "";
dg.DataSource = ds.Tables[0];
}
catch (Exception e)
{
MessageBox.Show("" + e.Message);
}
cn.Close();
}
Yes, there is. You can loop through the rows and set unwanted:
Me.dgwList.Rows(0).Visible = False
However, I would strongly advice to avoid it.
A better way would be to storing your dataset into a Datatable1 like:
' define those as *global* variables (outside subs and functions)
Dim dtMyTable1 as New Datatable
Dim dtMyTable2 as New Datatable
' Load your data from database into first dtMyTable and assign it to DGW
' instead of datasource
dtMyTable1 = ds.tables(0)
Me.dgwList.datasource = dtMyTable1
If you needed to update a list of second DGW every time user clicked a list, then you'd manipulate data into DataTable2 like:
Private Sub UpdateSelection()
For ir = 0 to me.dtMyTable.Rows.Count - 1
Dim dr as datagridviewRow = me.dtMyTable.Rows(ir)
If dr("Brand") = BrandString Then
dtMyTable2.ImportRow(dtMyTable.Item(I).Row)
End If
Next ir
End Sub
But to make a list to add up every next selected value, call this function:
Private Sub AddSelectedRowToSelection()
If Me.dgwList.SelectedRows.Count > 0 Then ' only if a row is selected
' add this row
dtMyTable2.ImportRow(dtMyTable.Item(Me.dgwList.SelectedRows(0).Index).Row)
End If
End Sub
And then put the second db into second DataGridView as datasource:
Me.SeconddgwList.datasource = dtMyTable2
You can empty the second list (delete rows but keep columns) like this:
dtMyTable2.Clear()
EDIT 2: Ahh, I see you're using it for collecting the rows from the first DataGridView. Then it's even simpler, do as above, but always set first table as datasource for the first datagridview and second table as source for second DataGridView. And do not remove old rows, keep them in the second set.
EDIT: Sorry, C# should be like this:
this.dgwList.Rows(0).Visible == false
Datatable dtMyTable = new Datatable();
Datatable dtMyTable2 = new Datatable();
dtMyTable = ds.tables(0);
for (ir = 0; ir <= this.dtMyTable.Rows.Count - 1; ir++) {
datagridviewRow dr = this.dtMyTable.Rows(ir);
if (dr("Brand") == BrandString) {
dtMyTable2.ImportRow(dtMyTable.Item(I).Row);
}
}
private void AddSelectedRowToSelection()
{
// only if a row is selected
if (this.dgwList.SelectedRows.Count > 0) {
// add this row
dtMyTable2.ImportRow(dtMyTable.Item(this.dgwList.SelectedRows(0).Index).Row);
}
}
this.dgwList.datasource = dtMyTable2;
I manage to solve my problem here is the code i used.
DataTable dt = new DataTable("Products");
private void dgvProductNew()
{
try
{
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString))
{
if (cnn.State == ConnectionState.Closed)
cnn.Open();
using (SqlDataAdapter da = new SqlDataAdapter("Select ProductID, BrandName, GenericName, Form, Dosage, Quantity, SellingPrice, D, VE from Products where Status = 'Active' and Quantity > 0", cnn))
{
da.Fill(dt);
dgvPOSproduct.DataSource = dt;
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
and
private void textOrderSearch_TextChanged(object sender, EventArgs e)
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("BrandName like '%{0}%' ", textOrderSearch.Text);
dgvPOSproduct.DataSource = dt;
dgvPOSproduct.Columns[0].HeaderText = "ProductID";
dgvPOSproduct.Columns[1].HeaderText = "Brand";
dgvPOSproduct.Columns[2].HeaderText = "Generic";
dgvPOSproduct.Columns[3].HeaderText = "Form";
dgvPOSproduct.Columns[4].HeaderText = "Dosage";
dgvPOSproduct.Columns[5].HeaderText = "Qty";
dgvPOSproduct.Columns[6].HeaderText = "Price";
dgvPOSproduct.Columns[7].HeaderText = "D";
dgvPOSproduct.Columns[8].HeaderText = "VE";
dgvPOSproduct.Columns[0].Width = 65;
dgvPOSproduct.Columns[1].Width = 80;
dgvPOSproduct.Columns[2].Width = 80;
dgvPOSproduct.Columns[3].Width = 58;
dgvPOSproduct.Columns[4].Width = 58;
dgvPOSproduct.Columns[5].Width = 45;
dgvPOSproduct.Columns[6].Width = 55;
dgvPOSproduct.Columns[7].Width = 35;
dgvPOSproduct.Columns[8].Width = 35;
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
if (txtSearch.Text != string.Empty)
{
foreach (DataGridViewRow row in gvProducts.Rows)//gvProducts is demo Grid
{
string text = "";
foreach (DataGridViewCell cell in row.Cells)
{
if ((cell.ColumnIndex != 0 && cell.ColumnIndex != 1))
{
text += cell.Value.ToString();
}
}
if (text.ToUpper().Contains(txtSearch.Text.ToUpper()))
{//to Uppper is not compulsory but its for case insensitivity
CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[gvProducts.DataSource];
currencyManager1.SuspendBinding();
row.Visible = true;
currencyManager1.ResumeBinding();
}
else
{
CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[gvProducts.DataSource];
currencyManager1.SuspendBinding();
row.Visible = false;
currencyManager1.ResumeBinding();
}
}
}
else
{
foreach (DataGridViewRow row in gvProducts.Rows)
{
CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[gvProducts.DataSource];
currencyManager1.SuspendBinding();
row.Visible = true;
currencyManager1.ResumeBinding();
}
}
}

Combobox in a datagridview

I want to put a combobox in my datagridview. I've tried differents ways (creating a var list<>, creating an arraylist, ect...) and none is working. The thing is my column already exist because of my select query that show my database in the datagridview. But the column is empty since in my database the column is fill with NULL value.
I have two choices : Creating a combobox and do an addcolumn, or if you know how to do it link my combobox to the already existing column. And obviously i need help creating my combobox.
Thank you !
My code :
public partial class Repair : Form
{
public Repair()
{
Main pp = new Main();
InitializeComponent();
this.label4.Text = pp.label3.Text;
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE FComponent IS NOT NULL";
}
else
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
ArrayList list = new ArrayList();
list.Add("C-C");
list.Add("C-O");
combo.Items.AddRange(list.ToArray());
dataGridView1.Columns.Add(combo);
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for(int i=0;i<4;i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataGridView2.Rows)
{
for(int i=0;i<3;i++)
{
dataGridView2.Columns[i].ReadOnly = true;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Main ff = new Main();
ff.Show();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
string Var1 = textBox1.Text;
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailAndPass WHERE BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE SerialNum LIKE #SerialNum AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE SerialNum LIKE #SerialNum And FComponent IS NOT NULL";
}
}
else
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailOnly WHERE (BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent) AND ReportingOperator IS NULL ";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL ";
command1.CommandText = "SELECT DISTINCT Machine, BoardName, BoardNumber FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
}
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[6].Value != null) && (bool)row.Cells[6].Value)
{
SqlCommand command = maConnexion.CreateCommand();
command = new SqlCommand("update FailAndPass set FaultCodeByOp=#Fault, RepairingDate=#RD, RepairingTime = #RT, ReportingOperator=#RO WHERE SerialNum=#Serial", maConnexion);
command.Parameters.AddWithValue("#Fault", row.Cells[4].Value != null ? row.Cells[4].Value : DBNull.Value);
command.Parameters.AddWithValue("#RD", DateTime.Today.ToString("d"));
command.Parameters.AddWithValue("#RT", row.Cells[5].Value != null ? row.Cells[5].Value : DBNull.Value);
command.Parameters.AddWithValue("#RO", this.label4.Text);
command.Parameters.AddWithValue("#Serial", this.textBox1.Text);
command.ExecuteNonQuery();
}
}
maConnexion.Close();
this.Hide();
Repair rep = new Repair();
rep.Show();
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.IsCurrentRowDirty)
{
dataGridView1.Rows[e.RowIndex].Cells[6].Value = true;
}
}
}
private void ComboboxInDatagridview()
{
var dataGridView1 = new DataGridView();
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { combo });
ArrayList list = new ArrayList() { "C-C", "C-O" };
var rowindex = dataGridView1.Rows.Add();
DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1["combo", rowindex];
//Or
//var columnindex = 0;
//DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1[columnindex, rowindex];
cmbCell.DataSource = list;
}
Anyone having other solutions ? I've tried something else :
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
ArrayList list1 = new ArrayList(); //{ "C-C", "C-O", "Absence composant", "Mauvaise valeur", "Mauvais sens", "Mauvais composant" };
list1.Add("C-C");
list1.Add("C-O");
combo.DataSource = list1;
combo.HeaderText = "FaultCodeByOp";
combo.DataPropertyName = "FaultCodeByOp";
dataGridView1.Columns.AddRange(combo);
didnt change anything.
I dont know what i've done, but it is not greyish anymore. Now it is white like other columns.... but it doesnt dropdown, nor show members of the list.

how do i convert or display the color base on the color code inside the datagridview cell?

I want to display a simple color on the background of the cells int the color column only?
how do I display the color instead of the color code atleast the background color of the cell itself? btw i'm using the fullrowselect..
my code for loading the database
SuspendLayout();
using (MySqlConnection conn = new MySqlConnection(myConnection))
{
//string cell = dataGridView3.CurrentCell.Value.ToString();
conn.Open();
string query = "SELECT productid,description,color,quantity,unitprice FROM deqor.tblproducts where category=?cat;";
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("?cat", comboBox1.SelectedItem.ToString());
try
{
sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
datset = new DataTable();
sda.Fill(datset);
bsource = new BindingSource();
bsource.DataSource = datset;
dataGridView1.DataSource = bsource;
DataGridViewColumn column = dataGridView1.Columns[0];
column.HeaderText = "Code";
column.Width = 160;
DataGridViewColumn column1 = dataGridView1.Columns[1];
column1.HeaderText = "Brand";
column1.Width = 220;
DataGridViewColumn column2 = dataGridView1.Columns[2];
column2.HeaderText = "Color";
column2.Width = 100;
DataGridViewColumn column3 = dataGridView1.Columns[3];
column3.HeaderText = "Quantity";
column3.Width = 50;
DataGridViewColumn column4 = dataGridView1.Columns[4];
column4.HeaderText = "Price";
column4.Width = 50;
sda.Update(datset);
if (dataGridView1.RowCount < 1)
{
datset.Clear();
string row = "NO items found";
datset.Rows.Add(row);
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
conn.Close();
}
ResumeLayout();
You could set the color during the CellFormatting event, see here for an explanation
Example
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//Check if we're formatting the color column
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Color")
{
//Make sure there's a value set
if (e.Value != null)
{
string colorCode = (string)e.Value;
ColorConverter cc = new ColorConverter();
e.CellStyle.BackColor = (Color)cc.ConvertFromString("#" + colorCode);
//If you don't want the code to show
e.Value = "";
e.FormattingApplied = true;
}
}
}
you can use foreach for every cell in column[2] and fill it like that:
dataGridView1.Rows[count].DefaultCellStyle.BackColor = (Color)ColorConverter.ConvertFromString("#FFDFD991");

Can not get last selected item in DataGridViewComboBoxCell

my problem is like that: I have a C# application having datagridview which has some textboxes and comboboxes in its columns. All the columns get the data from a database. Textboxes are readonly. When i ask for values in each row, i get the last selected component's value (i.e. combobox' value because textboxes are readonly) as null.
For example:
I have 10 cells in a row. The comboboxes are at 7th, 8th and 9th indexes in a row, where indexes from 0 to 6 are texboxes. When i select 3 of them (in order of 7, 8, 9) i cannot get the cell value of 9.
row.Cells[7].Value is OK,
row.Cells[8].Value is OK, and
row.Cells[9].Value is null
When i select any two of them let say first 8 and then 7, i cannot get the cell value of 7.
row.Cells[8].Value is OK and
row.Cells[7].Value is null
When i select only one item let say 9, i got the cell value again null.
As a result i get the last selected DataGridViewComboBoxCell as null.
Can anyone help me in my problem please? Thanks for all your help.
Here is my code:
private void cmbVariable_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = sender as ComboBox;
BringQuery(cmb.SelectedItem.ToString());
}
private void BringQuery(string option)
{
SqlConnection conn = new SqlConnection("Server = 10.2.6.14; Database = TTS; uid = myuser; password = mypassword");
DataTable dt1 = new DataTable();
SqlCommand cmd1 = new SqlCommand("select Track_Number, Parking_Area, Mission_Number, Track_Info, Time, Direction, Explanation from Traffic_Run_Table where Op_Type=#myType", conn);
SqlCommand cmd2 = new SqlCommand("select * from Traffic_Track_Table", conn);
SqlCommand cmd3 = new SqlCommand("select * from Traffic_Driver order by Id_Number", conn);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
cmd1.Parameters.Add(new SqlParameter("myType", option));
try
{
conn.Open();
sda1.Fill(dt1);
dataGridView2.AutoGenerateColumns = false;
foreach (DataGridViewColumn col in dataGridView2.Columns)
{
col.DataPropertyName = col.Name;
}
dataGridView2.DataSource = dt1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
DataGridViewComboBoxColumn cmbCol1, cmbCol2, cmbCol3;
SqlDataAdapter sda2 = new SqlDataAdapter(cmd2);
DataTable dt2 = new DataTable();
try
{
cmbCol1 = new DataGridViewComboBoxColumn();
cmbCol1.HeaderText = "Track 1";
cmbCol1.Name = "Track1";
cmbCol1.DataPropertyName = cmbCol1.Name;
cmbCol1.ValueType = typeof(int);
cmbCol1.Width = 50;
cmbCol2 = new DataGridViewComboBoxColumn();
cmbCol2.HeaderText = "Track 2";
cmbCol2.Name = "Track2";
cmbCol2.DataPropertyName = cmbCol2.Name;
cmbCol2.ValueType = typeof(int);
cmbCol2.Width = 50;
sda2.Fill(dt2);
dt2.Columns[0].ColumnName = "Track";
foreach (DataRow dr in dt2.Rows)
{
cmbCol1.Items.Add(Convert.ToInt32(dr["Track"]));
cmbCol2.Items.Add(Convert.ToInt32(dr["Track"]));
}
dataGridView2.Columns.Add(cmbCol1);
dataGridView2.Columns.Add(cmbCol2);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlDataAdapter sda3 = new SqlDataAdapter(cmd3);
DataTable dt3 = new DataTable();
try
{
cmbCol3 = new DataGridViewComboBoxColumn();
cmbCol3.HeaderText = "Driver";
cmbCol3.Name = "Driver";
cmbCol3.DataPropertyName = cmbCol3.Name;
cmbCol3.ValueType = typeof(string);
cmbCol3.Width = 260;
sda3.Fill(dt3);
dt3.Columns[0].ColumnName = "Id";
dt3.Columns[1].ColumnName = "Driver";
dt3.Columns[2].ColumnName = "Mission";
foreach (DataRow dr in dt3.Rows)
{
cmbCol3.Items.Add(Convert.ToString(dr["Id"]).Trim() + " - " + Convert.ToString(dr["Dirver"]).Trim() + " - " + Convert.ToString(dr["Mission"]).Trim());
}
dataGridView2.Columns.Add(cmbCol3);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
public string CheckNull(object value, Type objType)
{
string retVal = string.Empty;
if (value == null || value.ToString() == " " || value.ToString() == "")
{
if (objType == typeof(int))
{
retVal = "0";
}
if (objType == typeof(string))
{
retVal = "-";
}
}
else
{
retVal = value.ToString();
}
return retVal;
}
private void Save_Click(object sender, EventArgs e)
{
SqlConnection connForSave = new SqlConnection("Server = 10.2.6.14; Database = TTS; uid = myuser; password = mypassword");
SqlCommand cmdForSave = new SqlCommand("insert into Traffic_Records values (#type, #trackNumber, #parkingArea, #missionNmb, #trackInfo, #time, #direction, #explanation, #track1, #track2, #driverId, #driverName, #driverMission, #date)", connForSave);
foreach (DataGridViewRow row in dataGridView2.Rows)
{
try
{
dataGridView2[7, row.Index].Selected = false;
dataGridView2[8, row.Index].Selected = false;
dataGridView2[9, row.Index].Selected = false;
connForSave.Open();
cmdForSave.Parameters.AddWithValue("type", CheckNull(cmbVairable.SelectedItem.ToString(), typeof(string)));
cmdForSave.Parameters.AddWithValue("trackNumber", Convert.ToInt16(CheckNull(row.Cells[0].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("parkingArea", CheckNull(row.Cells[1].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("missionNmb", Convert.ToInt16(CheckNull(row.Cells[2].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("trackInfo", CheckNull(row.Cells[3].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("time", CheckNull(row.Cells[4].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("direction", CheckNull(row.Cells[5].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("explanation", CheckNull(row.Cells[6].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("track1", Convert.ToInt16(CheckNull(row.Cells[7].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("track2", Convert.ToInt16(CheckNull(row.Cells[8].Value, typeof(int))));
string[] sArray = null;
if (string.Compare(CheckNull(row.Cells[9].Value, typeof(string)), "0") != 0 && string.Compare(CheckNull(row.Cells[9].Value, typeof(string)), "-") != 0)
{
sArray = row.Cells[9].Value.ToString().Split('-');
sArray[0] = sArray[0].Remove(sArray[0].Length - 2, 1);
sArray[1] = sArray[1].Remove(0, 1);
sArray[1] = sArray[1].Remove(sArray[1].Length - 2, 1);
sArray[2] = sArray[2].Remove(0, 1);
}
else
{
string temp = "0 - -";
sArray = temp.Split(' ');
}
cmdForSave.Parameters.AddWithValue("driverId", Convert.ToInt16(sArray[0]));
cmdForSave.Parameters.AddWithValue("driverName", sArray[1]);
cmdForSave.Parameters.AddWithValue("driverMission", sArray[2]);
cmdForSave.Parameters.AddWithValue("date", DateTime.Now);
cmdForSave.ExecuteNonQuery();
cmdForSave.Parameters.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n Line Number: " + ex.LineNumber());
}
connForSave.Close();
}
}
This happens because DataGridView does not commit user made changes instantly but only after row is validated (I think, may be wrong here). So after you selected last value and did not change row (so validate event has not fired) the value in combo box is still null.
To fix this add CurrentCellDirtyStateChanged (more info here MSDN event to your grid:
private void GridCurrentCellDirtyStateChanged(object sender, EventArgs e)
{
dgvAssignedProperties.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
and this why new values are committed right away.

Combobox in DataGridView

How to display text on combo box in a DataGridView at run time from database?
For example, if am updating my text in database from combo box in DataGridView next time I want to display that text in combobox column.
sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
selectQueryString = "SELECT Code,CompanyName,FinancialYearStart,FinancialYearEnd,UserName,RoleP FROM CompanyInformation";
sqlDataAdapter = new SqlDataAdapter(selectQueryString, sqlConnection);
sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
dataGridView3.DataSource = bindingSource;
dataGridView3.Controls.Clear();
DataGridViewComboBoxColumn comboboxColumn = new DataGridViewComboBoxColumn();
comboboxColumn.Items.AddRange("Protected", "UnProtected");
comboboxColumn.HeaderText = "RoleP";
dataGridView3.Columns.Add(comboboxColumn);
private void button10_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
con.Open();
// if (dataGridView3.Columns.Count >= 4 && dataGridView3.Columns.Count < 10)
// {
int i = dataGridView3.Rows.Count;
int r = 0;
for (int s = 0; s < i; s++)
{
try
{
string Role = dataGridView3.Rows[s].Cells[0].Value.ToString();
int Cod = Convert.ToInt32(dataGridView3.Rows[s].Cells[1].Value.ToString());
if (Role != "")
{
SqlCommand cmd = new SqlCommand("update CompanyInformation SET RoleP=#Role where Code=#Cod", con);
cmd.Parameters.AddWithValue("#Cod", Cod);
cmd.Parameters.AddWithValue("#Role", Role);
r = cmd.ExecuteNonQuery();
}
}
catch
{
}
}
if (r >= 1)
{
MessageBox.Show("Update Successful");
SuperUser obj = new SuperUser();
this.Hide();
this.ParentForm.Hide();
}
You can go with this:
DataGridViewComboBoxColumn comboboxColumn = new DataGridViewComboBoxColumn();
comboboxColumn.Items.AddRange("Protected", "UnProtected");
comboboxColumn.HeaderText = "RoleP";
dataGridView3.Columns.Add(comboboxColumn);
After that check
foreach (DataGridViewRow row in dataGridView3.Rows)
{
(row.Cells[1] as DataGridViewComboBoxCell).Value = yourvalue;
}

Categories