How to Match two comboboxes items together - c#

I’ve two comboboxes which should contain two different informations.
1.cb1: select table_name from information_schema.tables (this display multiple tables)
2.cb2: should populate it with a column name.
Example: I've three tables in cb1 with the same attributes but have different values at the column EmpName (tblLondon,tblBerlin,tblRom,...)
Now I wanna display in second comboboxe the column EmpName dynamically whenever I choose a table in first combobox.
cb1[tblLondon] cb2[John,Mavis,Chris,Mike..]
OR
cb1[tblBerlin] cb2[Günther,Peter, Sophie,Sunny, ..]
Can u plz help me out
string C = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlConnection con = new SqlConnection(C);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME ASC");
try
{
// Open connection, Save the results in the DT and execute the spProc & fill it in the DT
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
cbTbl.DisplayMember = "TABLE_NAME";
cbTbl.ValueMember = "TABLE_NAME";
//Fill combobox with data in DT
cbTbl.DataSource = dt;
// Empty bzw. clear the combobox
cbTbl.SelectedIndex = -1;
This code is working and populating my cb1 (combobox)
And now i don't really know how to go about with cb2
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}

if I understand you correctly, and if you have this data in SQL server or other database you should use SelectedIndexChange event and load item for that Id (use Display Member and Value Member for match Id).
take a look at this.it might help you
Edit :
you can do this with below code : (if you don't use database)
you should use this code in cb1.SelectedIndexChange (or value)
var cb2items = new Dictionary<int, string> {{1, "Name"}, {1, "anotherName"},{2,"Name"},{2, "anotherName"}}; // use the number for parent Id in cb1
foreach (var item in cb2items)
{
if (item.Key == int.Parse(comboBox1.SelectedValue.ToString()))
{
comboBox2.Items.Add(item);
}
}
Edit 2 :
use this code in cb1.SelectedValueChange:
string C = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlConnection con = new SqlConnection(C);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("SELECT ... WHERE TableName = cb1.SelectedValue");
spProc & fill it in the DT
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
cbTbl.DisplayMember = "TABLE_NAME";
cbTbl.ValueMember = "TABLE_NAME";
cbTb2.DataSource = dt;
and you also can create a procedure that send back the items from table name as input. if you use procedure, your code perform better.
Edit 3 :
put this code in cbTb2.SelectedValueChange event :
try
{
int a = int.Parse(cbTB2.SelectedValue.ToString());
}
catch { }

You might want to see combobox's events, "SelectedIndexChanged" or "SelectedValueChanged" should do it

Related

Column 'Value' does not belong to table

I have stored some number data under column name Value in the tblV table of my database. I want to put the data from that column Value into textbox1.
But whenever I click the button it shows Column 'Value' does not belong to table error even though there is column Value in the table. What is causing this problem?
The first one is class and second one is the code on button click event.
public DataTable GetMaxno(decimal Licenseno)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;");
string sql = "select Max(Value) from tblv where Licenseno=#licenseno";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Licenseno",Licenseno );
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
da.Fill(DT);
return DT;
}
tryv tv = new tryv();
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = tv.GetMaxno(Convert.ToDecimal(textBox2.Text));
if (dt.Rows.Count > 0)
{
textBox1.Text= dt.Rows[0]["Value"].ToString();
}
}
Reason might be that your query does not return any aliases as Value. You can solve this with select Max(Value) as Value but instead of that, use ExecuteScalar instead which is exactly what you want. It returns first column of the first row.
A few things more;
Use using statement to dispose your connection and command.
Do not use AddWithValue. It may generate unexpected and surprising result sometimes. Use Add method overloads to specify your parameter type and it's size.
public int GetMaxno(decimal Licenseno)
{
using(var con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;")
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "select Max(Value) from tblv where Licenseno = #licenseno";
cmd.Parameters.Add("#licenseno", SqlDbType.Decimal).Value = Licenseno;
con.Open();
return (int)cmd.ExecuteScalar();
}
}
Then you can do;
textBox1.Text = tv.GetMaxno(Convert.ToDecimal(textBox2.Text)).ToString();
try
string sql = "select Max(Value) as Value from tblv where Licenseno=#licenseno";

Change tables loaded in the grid with dropdownlist

I am doing this for my own learning. It is not home work. All example I have found are for asp solutions.
I have a Grid and a DropDownList in a Winform.
The Grid has a DataSet a BindingSource and a TableAdapter.
I populate the dropdownlist with the tables in the DB as following:
public void FillDropDownList(string connString)
{
String Query = "SELECT * FROM information_schema.tables where Table_Name like 'Table%'";
using (var cn = new SqlConnection(connString))
{
cn.Open();
DataTable dt = new DataTable();
try
{
SqlCommand cmd = new SqlCommand(Query, cn);
SqlDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (SqlException e)
{
//to be completed
}
radDropDownList1.DataSource = dt;
radDropDownList1.ValueMember = "TABLE_NAME";
radDropDownList1.DisplayMember = "TABLE_NAME";
}
}
The line that loads the data in the grid is like this:
this.table_xxxTableAdapter.Fill(this.xxxDataSet.Table_xxx);
So I suspect that with these components I would need a new dataset for each table but I do not like to do that because new tables may be created in the future.
How can I change the table loaded in the grid selecting tables from the dropdownlist?
A DataSet requires that you specify the tables you may want to load at design time, but it sounds like you want to load these tables dynamically (because they may get added to the database from another source?)
If I'm understanding your question correctly, you should simply do this:
Whenever the user selects a table, load the selected table using a dynamic query and re-databind the grid to it. The code should look something like this. Note: This is untested code.
protected void radDropDownList_OnSelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string query = BuildQuery(radDropDownList.SelectedValue); //Pass in the table name
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
ad.Fill(dt);
}
}
catch (SqlException e)
{
//TODO: Handle this exception.
}
}
radGrid.DataSource = dt;
radGrid.DataBind();
}
private string BuildQuery(string table)
{
//TODO: Provide your own implementation for your query.
return string.Format(
#"SELECT * FROM {0}", table);
}

Delete is not working in selected data at Datagrid view

I am trying to delete selected data from datagrid and database at the same time when user clicks on "Delete". It is not working and error message shows that "Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"
Can anyone help me out this coding.
private void btnDeleteCustomer_Click(object sender, EventArgs e)
{
string strSqlConnection = #"Data Source = KK\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = JeanDB";
if ((dgvCustomerView.Rows.Count>0) && (dgvCustomerView.SelectedRows[1].Index != dgvCustomerView.Rows.Count))
{
SqlConnection sqlconn = new SqlConnection(strSqlConnection);
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);
sqlconn.Open();
DataTable dtEmployee = new DataTable("Customers");
sdaCustomer.Fill(dsCustomers, "Customers");
sqlconn.Close();
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
MessageBox.Show("Deleted Successfully");
}
}
Instead of Remove you can rebind grid:
dgvEmpView.DataSource = dsCustomers;
dgvEmpView.DataBind();
MessageBox.Show("Deleted Successfully");
and for deletion ExecuteNonQuery is used:
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
sqlconn.Open();
cmd.ExecuteNonQuery();
Unless you have two rows selected referencing the SelectedRows[1] is wrong. The array indexes start always with zero. (Probably it is just a type because the other lines references correctly the row to be deleted)
if ((dgvCustomerView.Rows.Count>0) &&
(dgvCustomerView.SelectedRows[0].Index != dgvCustomerView.Rows.Count))
{
....
but then, to delete the row in the database, you don't need to use an SqlDataAdapter.
You could work directly with a SqlCommand
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
cmd.Parameters.AddWithValue("#iCustomerID", iCustomerID);
sqlconn.Open();
cmd.ExecuteNonQuery();
finally you could simply remove the selected row from the grid without further query
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
If do not use sql parameters then use plain sql query.
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = "+ iCustomerID.ToString();
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);

C# mysql UPDATE and SELECT in one button

Im beginner in C#, but i have to make one software for friend. Its for generating numbers (they are in mysql). I have number in label and button. This button is for generate next number from MySQL (it SELECT number from database, which was not used).
My code:
private void button1_Click(object sender, EventArgs e)
{
string input = label1.Text.Trim();
string conn = "server=46.28.110.147;user=______;password=________;database=________;";
MySqlConnection myconn = new MySqlConnection(conn);
string sql = "SELECT numbers FROM domestic WHERE used=0 ORDER BY numbers LIMIT 1";
string sq2 = "UPDATE domestic SET used = 1 WHERE numbers = '" + label1.Text +"'";
MySqlDataAdapter da = new MySqlDataAdapter(sql, myconn);
MySqlCommand cmd = new MySqlCommand(sq2, myconn);
DataTable dt = new DataTable();
da.Fill(dt);
myconn.Open();
cmd.ExecuteNonQuery();
myconn.Close();
label1.Text = dt.Rows[0][0] + "";
}
Problem is when i click on button.
1) click on button - it make UPDATE (without SELECT) (it set used = 1 to number in database, which is in label)
2) click on button again - it make only SELECT (it takes next number from databse with used = 0)
3) click on button - it make only UPDATE (without SELECT)
4) clcik on button - AGAIN from step 2 to 3
Please, can you tell me, how can i do both operations (UPDATE and SELECT) in only one click?
Thanks and sorry for my bad english.
Your code looks like it currently behaves as follows:
Defines SELECT statement using a constant SQL query.
Defines UPDATE statement using the content of the label text (maybe empty?)
Fills a datatable with a MySqlDataAdapter. It must be recovering the first available number from your database.
Opens a connection and executes the update.
Recovers de first column of first datarow filled in point 3.
I think that the problem in this case is that you are mixing code to reach the solution. Try this:
Define SELECT statement using a constant SQL query.
Fill a datatable with a MySqlDataAdapter.
Recover the first column of first datarow filled in point 2 and populate value to the label text.
Define UPDATE statement using the content of the label text (this
time has the number recovered in the last step.
Open a connection and execute the update.
Something like...
private void button1_Click(object sender, EventArgs e)
{
string input = label1.Text.Trim();
string conn = "server=46.28.110.147;user=______;password=________;database=________;";
MySqlConnection myconn = new MySqlConnection(conn);
string sql = "SELECT numbers FROM domestic WHERE used=0 ORDER BY numbers LIMIT 1";
MySqlDataAdapter da = new MySqlDataAdapter(sql, myconn);
DataTable dt = new DataTable();
da.Fill(dt);
label1.Text = dt.Rows[0][0] + ""; // Recovers the value and puts into label.
MySqlCommand cmd = new MySqlCommand(sq2, myconn);
string sq2 = "UPDATE domestic SET used = 1 WHERE numbers = '" + label1.Text +"'";
myconn.Open();
cmd.ExecuteNonQuery(); // Updates database to set used = 1 for recovered number.
myconn.Close();
}
Try this:
private void button1_Click(object sender, EventArgs e)
{
string input = label1.Text.Trim();
string conn = "server=46.28.110.147;user=______;password=________;database=________;";
string sql = "SELECT numbers FROM domestic WHERE used=0 ORDER BY numbers LIMIT 1; UPDATE domestic SET used = 1 WHERE numbers = #numbers";
MySqlConnection myconn = new MySqlConnection(conn);
MySqlCommand cmd = new MySqlCommand(sql, myconn);
MySqlDataAdapter da = null;
DataSet ds = null;
DataTable dt = null;
cmd.Parameters.Add("numbers", SqlDbType.VarChar, 50).Value = input;
da = new MySqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0) {
if (ds.Tables(0).Rows.Count > 0) {
dt = ds.Tables(0);
label1.Text = dt.Rows(0)(0) + "";
}
}
}

Question about displaying sql server data in a grid

I am pulling data from a sql server and putting it into a grid using c#. When the data displays on the grid, it is showing up as the guid rather than the actual name. How do I get the name to show and not the uniqe identifier. Any ideas? Thanks.
Here is some of the code:
public InventoryWindow()
{
InitializeComponent();
if (dgDataView != null)
{
SqlConnection con = new SqlConnection(connString);
SqlDataAdapter adpt = new SqlDataAdapter("select * from Item", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "Item");
dgDataView.DataContext = ds;
//dgDataView.DataMember = "Item";
showdata();
}
}
private void showdata()
{
String connString = "server=server;database=database;user=user;password=password";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Item", con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
You are using select * from Item and therefore returning all columns. You could just specify the columns you want in the Grid, in the order you want them. The grid by default has autocolumn generation on.
You can also specify the columns you want and what fields they map to using the columns DataMember values.
I figured this out, I just wrote my own query to display certain columns instead of automatically showing all of them.

Categories

Resources