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;
}
Related
I am working a project and i need to display on a form (frmCaterlogs) a list of items. I have successfully implimented a custom list using a user control & FlowLayOutPanel. However now i am stuck on how i can bind my caterlogs that sits on a sql database to my custom list: Here is my code. on the custome_list(CatList), i have 4 controls, Id, Titile, Description, Icon stored in database as binarydata in the sqldb. I am lost on how i can bind data to the custom list control that can look thought all the records in my database. Thanking you all in advace for your kind advices.
private void PopulateCatelog()// This code is triggered when frmcaterlogs loads.
{
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ListView Items = new ListView()
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows) // This is where i am stuck
{
CatList iList = new CatList(dr["Item"].ToString());
iList.Title = dr;
}
CatList[] ListItem = new CatList[l];
//Loop though to check each item
for (int i = 0; i < ListItem.Length; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = fetch data for a list;
ListItem[i].Message = "fetch data for a lis";
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
I got the desired result after altering the code as seen below
private void FrmCatalogs_Load(object sender, EventArgs e)
{
PopulateCatelog();
}
private void PopulateCatelog()
{
//Populate your listitem here
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["Item"].ToString());
ListViewItem des = new ListViewItem(dr["Item_Description"].ToString());
CatList[] ListItem = new CatList[l];
for (int i = 0; i < ListItem.Length - l +1 ; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = item.Text;
ListItem[i].Message = des.Text;
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
}
}
Why do I get the value System.Data.DataRowView? c# + sqlserver
I'm trying to add data to my table but ne system.Data.rowview and I don't know how to do it so that it doesn't come out
Why do I get the value System.Data.DataRowView? c# + sqlserver
This is where I load the items inside the Checklixbox
public void Cargar_Requerimientos(string Id_CR)
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT Id_CR, Requisitos, Id_RS FROM Requerimientos WHERE Id_CR =#Id_CR ", cn);
cmd.Parameters.AddWithValue("Id_CR", Id_CR);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cn.Close();
//DataRow dr = dt.NewRow();
//dr["Requisitos"] = "Seleciona un Requisitos";
// dt.Rows.InsertAt(dr, 0);
///////////////////////////////////////
checkedListBox1.ValueMember = "Id_RS";
checkedListBox1.DisplayMember = "Requisitos";
checkedListBox1.DataSource = dt;
//bool state = true;
// for (int i = 0; i < checkedListBox1.Items.Count; i++)
// checkedListBox1.SetItemCheckState(i, (state ? CheckState.Checked : CheckState.Unchecked));
//dr = dt.NewRow();
enter code here
try
{
//checkedListBox1.DataSource = dt.Columns[0].ToString();
//dt.Columns[0].ToString();
//checkedListBox1.DataSource = dt.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
here I upload the data from combobox1 to checklistbox1
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// checkedListBox1.Enabled = false;
{
if (comboBox1.SelectedItem.ToString() == null)
{
checkedListBox1.Enabled = true;
}
}
if (comboBox1.SelectedValue.ToString() != null)
{
string Id_CR = comboBox1.SelectedValue.ToString();
Cargar_Requerimientos(Id_CR);
}
Result:
The CheckListBox does not directly support a DataSource, which is why the property is hidden from intellisence.
Usually it is correct to set the DataSource after setting the DisplayMember and ValueMember properties, to avoid multiple refresh calls, but to avoid your issue, you have to set the DataSource property first:
checkedListBox1.DataSource = dt;
checkedListBox1.ValueMember = "Id_RS";
checkedListBox1.DisplayMember = "Requisitos";
When I use the scanner to scan the barcode,
the item will be add in the first row and when I scan the second barcode,
the item will no add in the datagridview but it just adds a row only.
My column in datagridview is productid, ProductName, Description, Stock, UOM, Price
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DataGridViewRow newRow = new DataGridViewRow();
if (textBox1.Text.Length != 0)
{
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.RowCount -1;
dataGridView1.Rows.Insert(i);
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[i].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[i].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = item[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = item[5].ToString();
}
}
}
}
Page Screenshots:
https://ibb.co/pJ0fnx7
Your approach if your productid is a unique key as it should be, will always be returning only one result, I really dont see the need of the foreach statement here. Moreover every time you open a conn to the database you should be closing it.
My approach with this in mind would be a little different this would be
Public Class clsConn
{
Public List<Data> getSomething()
var SqlConn = new SqlConnection("your connection");
try
{
SqlConn.Open();
string sqlstring = "your sql sentence";
SqlCommand SqlCmd = new SqlCommand(sqlstring, SqlConn);
SqlDataReader reader = SqlCmd.ExecuteReader();
List<Data> dataList = new List<Data>();
if (reader.Read())
{
Data data = new Data();
data.productid = reader[0].ToString(); // this is just an example
dataList.Add(data);
}
return dataList;
}
catch (Exception ex)
{
MessageBox.Show("conexion to DB failed: " + ex.Message);
throw;
}
finally
{
SqlConn.Close();
}
}
}
}
And you should have a public data class that has all the properties you need like this for example
public class Data
{
public string productid { get; set; }
}
To use it, you have to work like this
List<Data> dbData = new List<Data>();
clsConn db = new clsConn();
dbData = db.getSomething();
//I ll leave the foreach but as I said this should be only one result
foreach (var item in DBData)
{
dataGridView1.Rows.Add(item.productid);
}
Your .Insert()-call does not provide the row to insert, and you do not handle the index returned from the Rows.Add()-call.
I have edited your code a bit so that it should work now.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode != Keys.Enter) || (textBox1.Text.Length == 0))
{
return;
}
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.Rows.Add();
DataGridViewRow row = dataGridView1.Rows[i];
row.Cells[0].Value = item[0].ToString();
row.Cells[1].Value = item[1].ToString();
row.Cells[2].Value = item[2].ToString();
row.Cells[3].Value = item[3].ToString();
row.Cells[4].Value = item[4].ToString();
row.Cells[5].Value = item[5].ToString();
}
}
And do not forget to close your database connection. Consider using the using-statement for this.
You should also check this: How to add a new row to datagridview programmatically
for example: I generate two combo-boxes box1 and box2 dynamically(on run time with a add button click) and on the selected index change of box1, items in box2 should be changed ;data in both boxes is fetched from database.
int cnt = 0;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection conb = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
public Form2()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
cnt++;
AddNewComboBox();
AddNewComboBox1();
}
private void AddNewComboBox()
{
ComboBox myNewComboBox = new ComboBox();
myNewComboBox.Name = "ComboBox1" + cnt.ToString();
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from company", con);
DataSet ds = new DataSet();
adp.Fill(ds, "company");
myNewComboBox.DataSource = ds.Tables["company"];
myNewComboBox.DisplayMember = ds.Tables["company"].Columns[0].ToString();
myNewComboBox.ValueMember = ds.Tables["company"].Columns[0].ToString();
//Program.counteritems = myNewComboBox.SelectedValue.ToString();
myNewComboBox.SelectedIndexChanged += new EventHandler(myNewComboBox_SelectedIndexChanged);
flowLayoutPanel1.Controls.Add(myNewComboBox);
con.Close();
}
private void AddNewComboBox1()
{
//string xyz = Program.counteritems;
ComboBox myNewComboBox1 = new ComboBox();
myNewComboBox1.Name = "ComboBox2" + cnt.ToString();
conb.Open();
SqlDataAdapter adp1 = new SqlDataAdapter("select * from company", con);
DataSet ds1 = new DataSet();
adp1.Fill(ds1, "company");
myNewComboBox1.DataSource = ds1.Tables["company"];
myNewComboBox1.DisplayMember = ds1.Tables["company"].Columns[1].ToString();
myNewComboBox1.ValueMember = ds1.Tables["company"].Columns[1].ToString();
//myNewComboBox_SelectedIndexChanged(sender);
myNewComboBox1.SelectedIndexChanged += new EventHandler(myNewComboBox1_SelectedIndexChanged);
flowLayoutPanel2.Controls.Add(myNewComboBox1);
//changefunction();
conb.Close();
}
void myNewComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var cbox1 = sender as ComboBox;
if (cbox1 != null)
{
if (cbox1.Name == "ComboBox1" + cnt.ToString())
{
var cbox2 = flowLayoutPanel2.Controls.OfType<ComboBox>().Where(c => c.Name == "ComboBox2" + cnt.ToString()).FirstOrDefault();
cbox2.SelectedValue = cbox1.SelectedValue.ToString();
con2.Open();
SqlDataAdapter adfgtyu = new SqlDataAdapter("select * from Cat_Comp_Item where (Category_Name='" + cbox1.SelectedText + "') ", con2);
DataSet dsft = new DataSet();
adfgtyu.Fill(dsft, "Cat_Comp_Item");
cbox2.DataSource = dsft.Tables["Cat_Comp_Item"];
cbox2.DisplayMember = dsft.Tables["Cat_Comp_Item"].Columns[1].ToString();
con2.Close();
}
}
//string combochange1 = ((ComboBox)sender).Text;
//if (!string.IsNullOrEmpty(myNewComboBox.SelectedValue.ToString()))
//{
// myNewComboBox1.SelectedValue = myNewComboBox.SelectedValue.ToString();
//}
}
private void Form2_Load(object sender, EventArgs e)
{
AddNewComboBox();
AddNewComboBox1();
}
void myNewComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Press OK to select this ");
}
I think you should bind first combobox value and second combobox add just text(---select---) on add button and letter on first combobox index change bind second combobox
You can do as below
private void myNewComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var cbox1 = sender as ComboBox;
if (cbox1 != null)
{
if (cbox1.Name == "ComboBox1")
{
var cbox2 = flowLayoutPanel2.Controls.OfType<ComboBox>().Where(c => c.Name == "ComboBox2").FirstOrDefault();
cbox2.SelectedValue = cbox1.SelectedValue.ToString();
}
}
}
To Do that you need to set comboBox2.ValueMember and comboBox1.ValueMember as same column in your company Table. select ID column or primary key column for that.
And also name your comboboxes as ComboBox1 and ComboBox2 when you create it like below
ComboBox myNewComboBox = new ComboBox();
myNewComboBox.Name = "ComboBox1";
And do the same for ComboBox2
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.