datagridviewcombobox columns Dependent on another column - c#

How To Do This Work on gridviewcomboboxcolumns any idea plx
//Form Load Event
string query="select article_name from article";
SqlCommmand cmd = new SqlCommand(query,con);
SqlDataAdapter da= new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
combobox1.items.clear();
for(int i=0;i<dt.rows.count;i++)
{
combobox1.items.add(dt.rows[i].cells[0].toString());
}
\ComboBox1 Selected IndexChange Event
string query1="select description from article where article_name='"+combobox1.selectedItem.ToString()+"'";
SqlCommmand cmd1 = new SqlCommand(query1,con);
SqlDataAdapter da1= new SqlDataAdapter(cmd);
DataTable dt1=new DataTable();
da1.Fill(dt1);
combobox2.items.clear();
for(int i=0;i<dt1.rows.count;i++)
{
combobox2.items.add(dt1.rows[i].cells[0].toString());
}
\Now Assume these 2 combox is gridviewCombobox Columns so how to make
this work on gridviewcombobox columns
Project in Windows Form in C#

I m posting this answer after a few months because its helps for
thoose whoose facing problem on DataGridviewComboboxcell
I did my own skill First Fill my first/Main Column
SqlCommand objCmd = new SqlCommand("select distinct article_name from Setup_article_custominvoice", con);
SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
DataTable dt = new DataTable();
objDA.Fill(dt);
article.DataSource = dt;
//this column1 will display as text
article.DisplayMember = "article_name";
After that i was going on Cell End Edit
if (dataGridView1.CurrentCell == dataGridView1.CurrentRow.Cells["article_name"])
{
string CategoryValue = "";
//string CategoryValue1 = "";
if (dataGridView1.CurrentCell.Value != null)
{
CategoryValue = dataGridView1.CurrentCell.Value.ToString();
//CategoryValue1 = dataGridView1.CurrentCell.Value.ToString();
}
//SqlConnection objCon = new SqlConnection(#"Data Source=.\SqlExpress;Initial Catalog=dbTest3;Integrated Security=True");
string query = "select article_name,composition from Setup_article_custominvoice where article_name='" + CategoryValue + "'";
SqlCommand objCmd = new SqlCommand(query, con);
SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
DataTable dt = new DataTable();
objDA.Fill(dt);
DataGridViewComboBoxCell t = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2] as DataGridViewComboBoxCell;
t.DataSource = dt;
t.DisplayMember = "composition";
}

Related

How to choose a name of data from sql table from another DataGridView using ComboBox in C#?

I have three tables: Patient, Doctor, Diagnosis. In the Diagnosis form I have two ComboBoxes, and I need to be able to choose the names of doctor and patient through these ComboBoxes.
Code of the methods:
void populatecombo()
{
string sql = "select * from Patient";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr;
try
{
conn.Open();
DataTable dt = new DataTable();
dt.Columns.Add("PatId", typeof(int));
rdr = cmd.ExecuteReader();
dt.Load(rdr);
PatId.ValueMember = "PatId";
PatId.DataSource = dt;
conn.Close();
}
catch
{
}
}
void populatedoc()
{
string mysql = "select * from Doctor";
SqlCommand cmd = new SqlCommand(mysql, conn);
SqlDataReader rdr;
try
{
conn.Open();
DataTable dt = new DataTable();
dt.Columns.Add("DocId", typeof(int));
rdr = cmd.ExecuteReader();
dt.Load(rdr);
DocId.ValueMember = "DocId";
DocId.DataSource = dt;
conn.Close();
}
catch
{
}
}
string patname;
string docname;
void fetchpatientname()
{
string mysql = "select * from Patient where PatId=" + PatId.SelectedValue.ToString() + "";
SqlCommand cmd = new SqlCommand(mysql, conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
patname = dr["PatName"].ToString();
PatientTb.Text = patname;
}
}
void fetchdoctorname()
{
string str = "select * from Doctor where DocId=" + DocId.SelectedValue.ToString() + "";
SqlCommand cmd = new SqlCommand(str, conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
docname = dr["DocName"].ToString();
DocName.Text = docname;
}
}
So populatedoc and populatecombo should get the names of doctor and patient, and fetch should help to choose them from ComboBox, but it doesn't seem to work with the error:
System.Data.SqlClient.SqlException: "Incorrect syntax near '='."
Picture of the form:
Based on my test, I could not get the error you provided based on your code.
You could try to use SqlCommand.Parameters.AddWithValue method to do it.
void fetchpatientname()
{
conn.Open();
string mysql = "select * from Patient where PatId=#PatId";
SqlCommand cmd = new SqlCommand(mysql, conn);
cmd.Parameters.AddWithValue("#PatId", cmbPat.SelectedValue);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
patname = dr["PatName"].ToString();
txtPatName.Text = patname;
}
conn.Close();
}
void fetchdoctorname()
{
conn.Open();
string str = "select * from Doctor where DocId=#DocId";
SqlCommand cmd = new SqlCommand(str, conn);
cmd.Parameters.AddWithValue("#DocId", cmbDoc.SelectedValue);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
docname = dr["DocName"].ToString();
txtDocName.Text = docname;
}
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
fetchdoctorname();
fetchpatientname();
}
Result:

Save edits from DataGridView to Datatable

Hi i want to save edits in DataGriView to datatable , i tried that code but an error shows 'System.ArgumentOutOfRangeException: 'The index was out of range. It must not be negative and must be smaller than the size of the collection.
Parameter name: index '' help
private void button11_Click(object sender, EventArgs e)
{
con.Open();
String query = "SELECT * FROM Taom";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
DataTable dt = new DataTable();
dataGridView1.DataSource = dt1;
SDA.Fill(dt);
dataGridView1.Rows[2].Cells[2].Value = Math.Atan((Convert.ToDouble(dataGridView1.Rows[5].Cells[2].Value)) / (Convert.ToDouble(dataGridView1.Rows[6].Cells[2].Value)));
dataGridView1.Rows[3].Cells[2].Value = Math.Atan((Convert.ToDouble(dataGridView1.Rows[7].Cells[2].Value)) / (Convert.ToDouble(dataGridView1.Rows[8].Cells[2].Value)));
ds1.Tables.Add(dt);
con.Close();}
I changed my code to that code no errors showed after i run values on datagridview change but no changes in datatable !!!
string query = "SELECT * FROM [dbo].[Taom]";
SqlConnection conn = new SqlConnection(#"Data Source=STE-P0024818PW;Initial Catalog=test;Integrated Security=True");
conn.Open();
SqlDataAdapter SDA = new SqlDataAdapter(query, conn);
DataSet ds1 = new DataSet();
DataTable dt = new DataTable();
SDA.Fill(dt);
dt.Rows[0]["Contents"] = "98"; //Before it was 10
dt.Rows[1]["Contents"] = "99"; //Before it was 11
ds1.Tables.Add(dt);
conn.Close();
Fill the right value inside your table and after pass the table rightly filled in your datasource, don't change this directly in the gridview like:
I try myself and it works:
private void Run()
{
string query = "SELECT * FROM dbo.[Anrufthema]";
SqlConnection conn = new SqlConnection("MyConnectionString");
conn.Open();
SqlDataAdapter SDA = new SqlDataAdapter(query, conn);
DataSet ds1 = new DataSet();
DataTable dt = new DataTable();
SDA.Fill(dt);
dt.Rows[0]["Anrufthema"] = "98"; //Before it was 10
dt.Rows[1]["Anrufthema"] = "99"; //Before it was 11
ds1.Tables.Add(dt);
conn.Close();
}
My Result, it works !

How to get the value in the combo box inside the dataGridview and put in my SQL Select Query?

I want to get the value of the combo box call dcourse to put it in my Sql select query but it is not working. this is my code
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dgEdit.DataSource = dt;
DataGridViewComboBoxColumn dcourse = new DataGridViewComboBoxColumn();
dcourse.HeaderText = "Course";
dcourse.Items.Add("AT (Automotive Technology)");
dcourse.Items.Add("CPT (Computer Technology)");
dcourse.Items.Add("ELT (Electrical Technology)");
dcourse.Items.Add("ICT (Instrumentation and Control Technology)");
dgEdit.Columns.Add(dcourse);
DataGridViewComboBoxColumn dname = new DataGridViewComboBoxColumn();
dname.HeaderText = "Student Name";
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Name from TBL_Student WHERE Course = '" +
dgEdit.CurrentRow.Cells[1].Value + "' ";
DataTable dat = new DataTable();
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(dat);
foreach (DataRow dr in dat.Rows)
{
dname.Items.Add(dr["Name"].ToString());
}
conn.Close();
dgEdit.Columns.Add(dname);
i am getting this pop up window and "dgEdit.CurrentRow.Cells1.Value" this should be the dcourse

Error displaying data from DB to predefined columns of datagrid View on button click event

I am using the following code:
string getinputs = "SELECT ir.plu_code PLU_Code,ir.barcode Barcode,ir.product_name Product_Name FROM inventory_register ir,inventory_value iv WHERE ir.dept_id='" + textBox1.Text + "' AND ir.barcode = iv.barcode";
connection.Open();
MySqlDataAdapter adapter = new MySqlDataAdapter(getinputs, connection);
MySqlCommandBuilder cmdbuilder = new MySqlCommandBuilder(adapter);
DataTable dt = new DataTable();
adapter.Fill(dt);
BindingSource bindsrc = new BindingSource();
DataGridView datagridv = new DataGridView();
bindsrc.DataSource = dt;
datagridv.DataSource = bindsrc;
connection.Close();
I have three predefined columns in datagridview1 say 'PLU_Code', 'Barcode' and 'Product_Name'.
I want to display the result (more than one row) of the select query in the datagridview. But I am not getting any.
How do I achieve this?
Try this code:
string getinputs = "SELECT ir.plu_code PLU_Code,ir.barcode Barcode,ir.product_name Product_Name FROM inventory_register ir,inventory_value iv WHERE ir.dept_id='" + textBox1.Text + "' AND ir.barcode = iv.barcode";
connection.Open();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(getinputs, connection);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
datagridview1.DataSource = table;
connection.Close();
I got the result. I achieved two empty rows on using #user4340666 code. when i scrolled the grid i found the set of data's been added as new columns leaving predefined column cells empty. so i just cleared the columns.
dataGridView1.Columns.Clear();
string getinputs = "SELECT ir.plu_code PLU_Code,ir.barcode Barcode,ir.product_name Product_Name FROM inventory_register ir,inventory_value iv WHERE ir.dept_id='" + textBox1.Text + "' AND ir.barcode = iv.barcode";
connection.Open();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(getinputs, connection);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
datagridview1.DataSource = table;
connection.Close();
Try this code:
string getinputs = "Select Query";
connection.Open();
MySqlCommandBuilder cmdbuilder = new MySqlCommandBuilder(getinputs,connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmdbuilder);
DataTable dt = new DataTable();
adapter.Fill(dt);
DataGridView datagridv = new DataGridView();
datagridv.DataSource = dt;
datagridv.DataBind();
connection.Close();

Populating a combolist automatically with data from SQL Server database

Can anyone help please, I am trying to populate the data automatically to my combobox without having to push any button, but by the dropdown control.....
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.AllowDrop == false)
{
SqlConnection conn = new SqlConnection("Data Source=localhost; database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Problem FROM PROBLEMT", conn);
DataTable dt = new DataTable();
DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = new SqlCommand("SELECT Problem FROM PROBLEMT", conn);
ad.Fill(ds, "Problem");
dataGridView1.DataSource = dt;
//Biding the data with the control
BindingSource bs = new BindingSource();
bs.DataSource = ds;
bs.DataMember = "Problem";
DataGridView dvg = new DataGridView();
this.Controls.Add(dvg);
dvg.DataSource = bs;
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox1.Items.Add(dt.Rows[i]["Problem"]);
}
}
else
{
}
}
you are missing a } and I hardly believe that SelectedIndexChanged is the best place to populate a combobox. Since obviously you are learning, try to put your code on a button, once it is working fine from the click of the button, you can look for a better place to it, like the form load for example.
also what exactly is the problem? does it give an error?
first create method for fetching data and load in combobox like this
protected void LoadCombo()
{
SqlConnection conn = new SqlConnection("Data Source=localhost;database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Problem FROM PROBLEMT", conn);
DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = new SqlCommand("SELECT Problem FROM PROBLEMT", conn);
ad.Fill(ds, "Problem");
dataGridView1.DataSource = ds;
dataGridView1.DataBind();
for (int X = 0; X <= ds.Tables[0].Rows.Count - 1; X++)
{
comboBox1.Items.Add(ds.Tables[0].Rows[X]["Problem"].ToString());
}
}
now on page_load call this method
protected void Page_Load()
{
if(ispostback)
{
}
else
{
LoadCombo();
}
}
Answer to the question on how to populate a combobox automatically:
private void Form3_Load(object sender, EventArgs e)
{
using (SqlConnection sc = new SqlConnection())
{
sc.ConnectionString= "database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30";
sc.Open();
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable data = new DataTable();
sda.SelectCommand = new SqlCommand("SELECT ID, TypeProblem FROM eL_Section", sc);
sda.Fill(data);
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "ID";
comboBox1.DataSource = data;
comboBox2.ValueMember = "TypeProblem";
comboBox2.DisplayMember = "TypeProblem";
comboBox2.DataSource = data;
}
}
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = "database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30";
cn.Open();
using (SqlDataAdapter da = new SqlDataAdapter())
{
DataTable dat = new DataTable();
da.SelectCommand = new SqlCommand("SELECT UserName FROM UserT", cn);
da.Fill(dat);
comboBox3.ValueMember = "UserName";
comboBox3.DisplayMember = "UserName";
comboBox3.DataSource = dat;
}
}
// TODO: This line of code loads data into the 'knowledgeEssentialsDataSet.ProblemT' table. You can move, or remove it, as needed.
this.problemTTableAdapter.Fill(this.knowledgeEssentialsDataSet.ProblemT);
}

Categories