Populating a combolist automatically with data from SQL Server database - c#

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);
}

Related

Clear DataGrid for new search result in c#

I was trying to clear the DataGrid for new result view but I couldn't. Is there any problem of my writing those code or anything else? Please help me on this. Here is the code:
private void btnsearch_Click(object sender, EventArgs e)
{
string sid = txtsid.Text;
string subject = cmbsubject.Text;
string term = txtterm.Text;
string year = cmbyear.Text;
string stclass = cmbclass.Text;
string connection = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\sms.mdf;Integrated Security=True";
string queryAll = "SELECT * FROM Result WHERE sid='"+sid+"' OR term='"+term+"' OR subject='"+subject+"' OR class='"+stclass+"' OR year = '"+year+"'";
SqlConnection con = new SqlConnection(connection);
con.Open();
SqlCommand cmd = new SqlCommand(queryAll, con);
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dataset = new DataTable();
sda.Fill(dataset);
BindingSource bs = new BindingSource();
bs.DataSource = dataset;
// dgResult is the changed name of the DataGridView
dgResult.DataSource = bs;
sda.Update(dataset);
}
catch (Exception ex)
{
MessageBox.Show(Convert.ToString(ex));
}
finally
{
con.Close();
}
}

fill grid view in c#

I am new in using visual studio and ADO.NET. I want to display result from sqlserver database in data gridview.
This is my code but it does not fill data to gridview.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand Cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(Cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
SqlDataReader reader = Cmd.ExecuteReader();
dt.Load(reader);
dataGridView1.DataSource = dt;
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
Why are you binding to grid two times?
If your application is ASP.NET Webforms and you are trying to bind the GridView(ID for the GridView is "dataGridView1"), then make your binding to single time and to bind data for GridView you need to use dataGridView1.DataBind(); after dataGridView1.DataSource = dt;
If your application is WindowsForms application then modify your code like below
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
string connectionString = "Define your connection string here";
using(SqlConnection con = new SqlConnection(connectionString ))
{
SqlCommand cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
}

datagridviewcombobox columns Dependent on another column

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";
}

Search data in two datagrids at same time

I have this two datagrids where JMBGvlasnika is in both of them same as BrojSasije.
For search I use this code:
DataView DV = new DataView(dbdt);
DV.RowFilter = String.Format("JMBGvlasnika LIKE '%{0}%'", textBox1.Text);
korisniciDataGridView.DataSource = DV;
Loading tables code:
private void svikorisnici_Load(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand(" SELECT * FROM Korisnici", konekcija);
SqlCommand cmd1 = new SqlCommand(" SELECT * FROM vozilo", konekcija);
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
dbdt = new DataTable();
sda.Fill(dbdt);
BindingSource kbs = new BindingSource();
kbs.DataSource = dbdt;
korisniciDataGridView.DataSource = kbs;
sda.Update(dbdt);
SqlDataAdapter sda1 = new SqlDataAdapter();
sda1.SelectCommand = cmd1;
DataTable dbdt1 = new DataTable();
sda1.Fill(dbdt1);
BindingSource kbs1 = new BindingSource();
kbs1.DataSource = dbdt1;
voziloDataGridView.DataSource = kbs1;
sda1.Update(dbdt1);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Problem is when I search by JMBGvlasnika I get search results only for 1st table
image link http://ge.tt/999Igxm/v/0?c
If I try to do this:
DataView DV1 = new DataView(dbd1t);
DV1.RowFilter = String.Format("JMBGvlasnika LIKE '%{0}%'", textBox1.Text);
voziloDataGridView.DataSource = DV1;
And start searching I get empty 2nd table, and if I delete what I wrote 2nd table is not filtering.
Can someone help me to make search in both datagrids in same time ?

Visual c# relatively dynamic comboboxes

I have two related comboboxes, combobox1 populate the items of combobox2. In combobox1 selectIndexChanged event I have this code but i have error Unknown column 'System.Data.DataRowView' in 'where clause'.
I tried to put this code in the SelectionChangeCommitted at first selection, it populate the right items, but my second selection i have error in comboBox2.Items.Clear(); states Items collection cannot be modified when the DataSource property is set. :( what to do.?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sql;
if (comboBox1.SelectedIndex >= 0)
{
comboBox2.Items.Clear();
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
sql = "SELECT brgyname,idbrgy from barangay where idmun=" + comboBox1.SelectedValue;
adapter.SelectCommand = new MySqlCommand(sql, conn);
DataTable cbBrgy = new DataTable();
adapter.Fill(cbBrgy);
comboBox2.DataSource = cbBrgy;
comboBox2.DisplayMember = "brgyname";
comboBox2.ValueMember = "idbrgy";
}
}
Here's how i populate combobox1
private void cbMun()
{
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand("SELECT munname,idmun from municipality", conn);
DataTable cbMun = new DataTable();
adapter.Fill(cbMun);
comboBox1.DataSource = cbMun;
comboBox1.DisplayMember = "munname";
comboBox1.ValueMember = "idmun";
}
while cbMun function is filling the combobox it will call combobox selected index change event directly , so to work around this define bool value comboisloading = true and modify your code such like below :
private void cbMun()
{
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand("SELECT munname,idmun from municipality", conn);
DataTable cbMun = new DataTable();
adapter.Fill(cbMun);
comboBox1.DataSource = cbMun;
comboBox1.DisplayMember = "munname";
comboBox1.ValueMember = "idmun";
comboisloading = false;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboisloading)
return;
string sql;
if (comboBox1.SelectedIndex >= 0)
{
comboBox2.Items.Clear();
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
sql = "SELECT brgyname,idbrgy from barangay where idmun=" + comboBox1.SelectedValue;
adapter.SelectCommand = new MySqlCommand(sql, conn);
DataTable cbBrgy = new DataTable();
adapter.Fill(cbBrgy);
comboBox2.DataSource = cbBrgy;
comboBox2.DisplayMember = "brgyname";
comboBox2.ValueMember = "idbrgy";
}
}
I just placed my code in comboBox1_SelectionChangeCommitted not in comboBox1_SelectedIndexChanged event since comboBox1.SelectedValue is still not generated not unless the user committed its changes to the items. Also my Items collection cannot be modified when the DataSource property is set error from comboBox2.Items.Clear(); i just deleted this line of code. I still clears and replace my combobox2 items properly. Hmm.. Since i used to clear comboboxes in vb..I wonder.
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
string sql;
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
sql = "SELECT brgyname,idbrgy from barangay where idmun=" + comboBox1.SelectedValue;
adapter.SelectCommand = new MySqlCommand(sql, conn);
DataTable cbBrgy = new DataTable();
adapter.Fill(cbBrgy);
comboBox2.DataSource = cbBrgy;
comboBox2.DisplayMember = "brgyname";
comboBox2.ValueMember = "idbrgy";
}

Categories