combobox items from the database - c#

In C# I used a combo box in my form and I wish to obtain a specific column from a table in the database and contents of the column to be added as the items in the combo box.
I have declared this way
string strCon, strQry;
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
SqlCommand comm;
den strcon= data source =" " initial catalog =" " use id =" " password=" ";
con = new sqlconnection(strcon);
strquery = select city from the cities;
da = new sqladapter(strqry,con);
ds = new dataset;
da.fill(ds, " cities");
Should I put for loop till items continue adding?
Update:
I want the entire column to be added as the items in the check box. On click of the check box, I want the entire column to be displayed as respective item in the check box.

comboBox1.Items.Add(drCities.Cells[0].Value);
comboBox1.Items.Add(drCities.Cells[1].Value);

Try this: if you want to display one column called 'Name' then...
comboBox1.DataSource = ds;
comboBox1.DisplayMember = "Name";
else, as you have described, you might want to do this...
foreach(DataRow drCities in ds.Tables[0].Rows)
{
string sValue = string.Format("{0} {1} {2}", drCity["Name"], drCity["Col1"], drCity["Col2"]);
comboBox1.Items.Add(sValue);
}
the above code would sit in the Form load event which is usually...
private void Form1_Load(object sender, EventArgs e)
{
....
}

Related

How do I select a value from a combo box to display an associated value in c#

I have a combo box within a WinForm using C# that displays a list of customer names from an MS Access Database. I have another textbox where I want to display the customer ID on the selection of the customer name using the combo box? The code I have used to display the list of names in the combo box is as follows;
public void homeFrm_Load(object sender, EventArgs e)
{
OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Carmine_Cycle_Couriers_Database.accdb");
OleDbDataAdapter da = new OleDbDataAdapter("SELECT CustomerID, FirstName from tblCustomer", cn);
DataSet dt = new DataSet();
da.Fill(dt, "FirstName");
cboCustomerSelect.DataSource = dt.Tables["FirstName"];
cboCustomerSelect.DisplayMember = "FirstName";
cboCustomerSelect.ValueMember = "CustomerID";
cboCustomerSelect.Text = "Select Customer";
}
You can use Value property of cboCustomerSelect to get the CustomerId. You can use combobox selectedindexchanged event and do the following
yourTextBox.Text = cboCustomerSelect.Value.ToString();

How To count updated same record row in db and show count number in label?

Here i have table name tblbb which have a column called journalname, textbox ,button and a label.I have store some data in tblbb. Now what i am trying to do is, to count same data row in column journalname when i input data data in textbox and on button click show the count in label.
for eg in tblbb
Journalname
a
a
b
b
if textbox.text="a"
label.text=2
But the problem is that when i update data in table the label text does not show the updated count for that data.For example if i store one more a in above table then on button click the must show lable.text=3,but instead of that it shows label.text=2 even the table is updated.
The method used
public DataTable getjournalcount(string journalname)
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
string sql = "select journalname, count(*) as dupes from tblbb group by journalname";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#JournalName", journalname);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
Code behind button
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = j.getjournalcount(TextBox1.Text);
if (dt.Rows.Count>0)
{
Label1.Text= dt.Rows[0]["dupes"].ToString();
}
}
modify your sql as
string sql = "select journalname, count(*) as dupes
from tblbb where where journalname=#journalname
group by journalname";

Adding Data in the datagridview

I have a little problem here, and I admit im not so very good at this but you guyz can help me, right?
so here my problem.
I created this codes:
private void button1_Click(object sender, EventArgs e)
{
connect = new OleDbConnection(coo);
connect.Open();
command.Connection = connect;
DataTable dt = new DataTable();
OleDbDataAdapter ODA = new OleDbDataAdapter("SELECT * FROM Items where itemno = '" + textBox1.Text + "'", connect);
ODA.Fill(dt);
dataGridView1.DataSource = dt;
}
which if I click my button "Enter" it can add or can insert data in the datagridview but if I click the "Enter" button again with another data, the previous data I,ve just entered was disappered and replace it with another one and all i want is add an another data by not replacing or deleting the other data i,ve just entered.
What should I do?
Using DataTable.Merge will append each successive DataTable to the previous one that was assigned to the DataGridView, as long as the schema (i.e. column types) is the same.
Replace this:
dataGridView1.DataSource = dt;
With this:
if (dataGridView1.DataSource == null)
dataGridView1.DataSource = dt;
else
((DataTable)dataGridView1.DataSource).Merge(dt);
I think you just need to do a databind.
Try adding dataGridView1.DataBind() to the end of your code.

getting value of combobox to textbox

using query i have called two columns value from database into one column. the point is now i want to select a value form combobox and put one column value into textbox.
e.g
two column values from database into combobox below
10001 haider <------ when i select this index i want only haider to be viewed into the textbox
10002 fahad
10003 aitazaz
the snippet which i have used for calling the two colums value from database is:
public void account()
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no, acc_name FROM accounts_record";
MySqlDataAdapter adpt = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbacc.Items.Add(ds.Tables[0].Rows[i][0] + " " + ds.Tables[0].Rows[i][1]);
}
con.Close();
}
You should be adding values and text to the combobox separately.
Here's an example ComboBox: Adding Text and Value to an Item (no Binding Source).
If you have to display the id in the text you have to do some parsing before putting the selected text into the textbox.
Use ComboBox.SelectedIndexChanged event of the combobox to populate the textbox accordingly. use http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindexchanged(v=vs.110).aspx
If you are able to get the 2 value text of the combo box on selection change then you can split it with space (" ") character and take the 2nd string and put it in textbox.
For example
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] splitedStr = comboBox1.SelectedText.Split(' ');
textBox1.Text = splitedStr[1];
}
You should use the code as below
private void Form1_Load(object sender, EventArgs e)
{
string conString = "Data Source=\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no +'-' + acc_name as AccNoWithName , acc_no as ActNo FROM accounts_record";
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet dsn = new DataSet();
adpt.Fill(dsn);
con.Close();
comboBox1.DisplayMember = "AccNoWithName";
comboBox1.ValueMember = "ActNo";
comboBox1.DataSource = dsn.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = comboBox1.SelectedValue.ToString();
}

Issue with Delete button in GridView in Visual Studio

This is my code:
private void Bind()
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\documents\visual studio 2012\Projects\CourseProjectCars\CourseProjectCars\DataCars.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from SuperCars", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\documents\visual studio 2012\Projects\CourseProjectCars\CourseProjectCars\DataCars.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand delcmd = new SqlCommand();
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
{
delcmd.CommandText = "DELETE FROM SuperCars WHERE Car='%" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "%'";
con.Open();
delcmd.Connection = con;
delcmd.ExecuteNonQuery();
con.Close();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
MessageBox.Show("Row Deleted");
}
Bind();
}
I want to put a delete button in my application. When I select a row and click the delete button, it throws the exception below:
Index was out of range. Must be non-negative and less than the size of the collection.
The problem is you don't know how to select a row as well as how the DataGridView understands when a row is called selected. To select a row, you have to click on the row header, or if you want to select the row just by clicking on any cell on the row, just set the property SelectionMode to DataGridViewSelectionMode.FullRowSelect. Then the SelectedRows should have at least 1 item, the index out of range exception should not be thrown any more.
If you intend to allow user to delete 1 row at a time, I think you can use the property CurrentRow to get the current selected row, you can also use the CurrentCell or CurrentCellAddress and derive the selected row from them.
Please display the code in side Bind() function. I think record was not removed in the database and when you call Bind() function at that time record again bind in the gridview.
I think your delete query is wrong , if you want to remove record which have car as cell[0] value so query will be as below :
delcmd.CommandText = "DELETE FROM SuperCars WHERE Car Like '%" +dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "%'";

Categories