Writing in combobox - c#

I have 3 comboboxes.
At first I imported the number of stations. Example 11650, 13450 and more.
When the user selects the number from the first combobox After automatically according to the station number in the second combobox After giving the date. Because each station dates are different.
My question to you is how I can do so if the user enters the number keys, in the second combobox to show dates?
My Code is :
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string MyConString1 = "SERVER=localhost;" +
"DATABASE=hydrodb;" +
"UID=root;" +
"PASSWORD=;";
MySqlConnection connection1 = new MySqlConnection(MyConString1);
string command1 = "select Dat FROM hydgod where Station=" + comboBox1.SelectedItem.ToString();
MySqlDataAdapter da1 = new MySqlDataAdapter(command1, connection1);
DataTable dt1 = new DataTable();
da1.Fill(dt1);
comboBox2.Items.Clear();
comboBox3.Items.Clear();
comboBox2.SelectedItem = -1;
comboBox3.SelectedItem = -1;
foreach (DataRow row in dt1.Rows)
{
string rowz = string.Format("{0}", row.ItemArray[0]);
comboBox2.Items.Add(rowz);
comboBox3.Items.Add(rowz);
}
connection1.Close();
}

I would suggest to get all corresponding dates into a List<string> and bind it as DataSource to the second ComboBox
List<string> dateList = new List<string>();
foreach (DataRow row in dt1.Rows)
{
dateList.Add(string.Format("{0}", row.ItemArray[0]);
}
comboBox2.DataSource = dateList;
EDIT:
I received the same values result in combobox. 2010-01-01 12:00:00AM
I want to cut the 12:00:00AM
If row.ItemArray[0] is of type DateTime you can try:
dateList.Add(row.ItemArray[0].ToString("yyyy-MM-dd));
if it is a simple string you can split it:
dateList.Add(row.ItemArray[0].Split(' ')[0]);
ps. to populate the 3-rd combobox also you can just hook the same List also to the 3-rd one:
comboBox3.DataSource = dateList;
Don't add the items manually and then hook the list to the DataSource. Do either or

Related

How to copy and save elements from dataGridView?

I would like to ask how to copy and save selected elements from one dataGridView to another? In one dataGridView, I have elements, that can be selected, and upon selection, they are then transferred to the other dataGridView, where they will be ready for printing on paper. However, with the code below, it doesn't copy the elements correctly, as it displays ContextMenuStrip, DefaultCellStyle, DividerHeight, etc...
It also doesn't save my selection, but instead overwrites it everytime I choose new rows. How exactly do you copy and save elements (rows) from one dataGridView to another? I would like to avoid doing it with clicking, as there will be multiples of elements that need to be ready for printing.
private void button5_Click(object sender, EventArgs e)
{
dataGridView2.DataSource = dataGridView1.SelectedRows;
}
This is my example, try to following this perhap?
if (GMDSP1.Rows.Count > 0)
{
DataTable _dt1 = new DataTable();
DataTable _dt2 = new DataTable();
DataGridViewRow gvdr = GMDSP1.CurrentRow;
DataRow[] drArr = _dt1.Select("Name= '" + gvdr.Cells["Name1"].Value.ToString() + "'");
if (drArr.Length > 0)
{
DataRow dr = _dt2.NewRow();
if (_dt2.Columns.Count == 0)
{
foreach (DataColumn dc in _dt1.Columns)
{
DataColumn newDC = new DataColumn(dc.ColumnName, dc.DataType);
_dt2.Columns.Add(newDC);
}
}
dr["ID"] = drArr[0]["ID"].ToString();
dr["Name"] = drArr[0]["Name"].ToString();
_dt2.Rows.Add(dr);
_dt1.Rows.Remove(drArr[0]);
_dt1.AcceptChanges();
_dt2.AcceptChanges();
GMDSP1.DataSource = _dt1;
GMDSP2.DataSource = _dt2;

Visual C# program saves only last index to XML file

private void button1_Click(object sender, EventArgs e) //add data to listBox
{
if (String.IsNullOrWhiteSpace(textBox1.Text) || String.IsNullOrWhiteSpace(textBox2.Text))
{
MessageBox.Show("Proszę uzupełnić wszystkie pola, aby wprowadzić dane", "Błąd!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
listBox1.Items.Add(textBox4.Text + " " + textBox1.Text + " " + textBox2.Text);
listBox1.DisplayMember = textBox4.Text;
}
private void button2_Click(object sender, EventArgs e) //delete data from listbox
{
if(listBox1.SelectedIndex == -1)
{
MessageBox.Show("Proszę zaznaczyć pozycję by usunąć", "Błąd!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
listBox1.Items.Remove(listBox1.SelectedItem);
}
private void button3_Click(object sender, EventArgs e) //save to XML button
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.TableName = "Tabela";
dt.Columns.Add("Name");
dt.Columns.Add("Surname");
dt.Columns.Add("PESEL");
dt.Columns.Add("Room");
ds.Tables.Add(dt);
foreach (string item in listBox1.Items)
{
DataRow dr = ds.Tables["Tabela"].NewRow();
dr["Name"] = textBox1.Text;
dr["Surname"] = textBox2.Text;
dr["PESEL"] = textBox3.Text;
dr["Room"] = textBox4.Text;
ds.Tables["Tabela"].Rows.Add(dr);
}
ds.WriteXml("D:\\data.xml");
}
private void button4_Click(object sender, EventArgs e) //read from XML button
{
DataSet ds = new DataSet();
ds.ReadXml("D:\\data.xml");
foreach (DataRow item in ds.Tables["Tabela"].Rows)
{
listBox1.Items.Add(string.Format("{0} {1} {2}", item["Room"], item["Name"], item["Surname"]));
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml("D:\\data.xml");
foreach (DataRow item in ds.Tables["Tabela"].Rows)
{
textBox1.Text = item["Name"].ToString();
textBox2.Text = item["Surname"].ToString();
textBox3.Text = item["PESEL"].ToString();
textBox4.Text = item["Room"].ToString();
}
}
I have a problem while saving and reading XML file. When I will add some data to listBox from textBoxes is saves only last index I added, but multiple times.
Example:
<Tabela>
<Name>John</Name>
<Surname>Johnson</Surname>
<PESEL>123465789</PESEL>
<Room>21</Room>
</Tabela>
<Tabela>
<Name>John</Name>
<Surname>Johnson</Surname>
<PESEL>123465789</PESEL>
<Room>21</Room>
</Tabela>
<Tabela>
<Name>John</Name>
<Surname>Johnson</Surname>
<PESEL>123465789</PESEL>
<Room>21</Room>
</Tabela>
And when I load data from XML the listBox works fine, but when I selected one index from this list in my textBoxes appears only last index, not that I have clicked.
In your code you have
dr["Name"] = textBox1.Text;
dr["Surname"] = textBox2.Text;
dr["PESEL"] = textBox3.Text;
dr["Room"] = textBox4.Text;
For each itteration in the listbox items. As the textboxes wont be changing it will indeed add one for each item in your listbox.
Im thinking you needed to do something with item, in your for loop, not the text boxes
foreach (string item in listBox1.Items)
{
DataRow dr = ds.Tables["Tabela"].NewRow();
dr["Name"] = textBox1.Text;
dr["Surname"] = textBox2.Text;
dr["PESEL"] = textBox3.Text;
dr["Room"] = textBox4.Text;
ds.Tables["Tabela"].Rows.Add(dr);
}
I'm not sure what do you want to do but you would probably want to change something like reading and writing from a list or something.
If you tell us the technology that you are using (asp.net, wpf, etc.), we probably can help you out.
You are using a very bad approach with a listbox control that represents your main business entity. This is very bad...
In fact in order to make to work your solution, you should save into xml file everytime you add a new item data in the expected text boxes and the avoid to loop the listbox items when saving...
Then it is wrong also the method to display the details of your selected item when occurs the SelectedIndexChanged event, because you don't point to the correct listbox item selcted, but to the last saved item in the file everytime you select a new item in your listbox.
So, a better approach could be declare a class that will be your entity and a Collection of this class that will be the datasource of your listbox:
public class Booking{
string Name;
string Surname;
string PESEL; //your key? remember to manage duplicates if you insert manually (better if it were generated automatically as unique data (Guid))
string Room;
}
System.Collections.Generic.List<Booking> bookings; //instantiate in Form constructor method
then, your UI controls event handlers will manage this objects in order to do your operations, and so:
When you add a new item:
if (String.IsNullOrWhiteSpace(textBox1.Text) || String.IsNullOrWhiteSpace(textBox2.Text))
{
MessageBox.Show("Proszę uzupełnić wszystkie pola, aby wprowadzić dane", "Błąd!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
bookings.Add(new Booking{
Name = textBox1.Text,
Surname = textBox2.Text,
PESEL = textBox3.Text,
Room = textBox4.Text
});
listBox.DataSource = null;
listBox.DataSource = bookings; //use the datasource property
listBox.DisplayMember = "Room";
listBox.ValueMember = "PESEL";
When you delete one item:
if (listBox.SelectedIndex == -1) {
MessageBox.Show("Proszę zaznaczyć pozycję by usunąć", "Błąd!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
bookings.Remove(bookings.Find(c => c.PESEL == listBox.SelectedValue as string));
listBox.DataSource = null;
listBox.DataSource = bookings; //use the datasource property
listBox.DisplayMember = "Room";
listBox.ValueMember = "PESEL";
When you save your items:
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.TableName = "Tabela";
dt.Columns.Add("Name");
dt.Columns.Add("Surname");
dt.Columns.Add("PESEL");
dt.Columns.Add("Room");
ds.Tables.Add(dt);
foreach (Booking item in bookings)
{
DataRow dr = ds.Tables["Tabela"].NewRow();
dr["Name"] = item.Name;
dr["Surname"] = item.Surname;
dr["PESEL"] = item.PESEL;
dr["Room"] = item.Room;
ds.Tables["Tabela"].Rows.Add(dr);
}
ds.WriteXml("D:\\data.xml");
When you load from file
//attention to eventual new records appended to the list you may lose them
DataSet ds = new DataSet();
ds.ReadXml("D:\\data.xml");
bookings.Clear(); //<<== avoids dirty loading (duplicates)
foreach (DataRow item in ds.Tables["Tabela"].Rows) {
bookings.Add(new Booking() {
Name = item["Name"].ToString(),
Surname = item["Surname"].ToString(),
PESEL = item["PESEL"].ToString(),
Room = item["Room"].ToString()
});
}
listBox.DataSource = null;
listBox.DataSource = bookings; //use the datasource property
listBox.DisplayMember = "Room";
listBox.ValueMember = "PESEL";
When you want display details of a selcted listbox item:
Booking booking = bookings.Find(c => c.PESEL == listBox.SelectedValue as string);
if (booking == null) return;
textBox1.Text = booking.Name;
textBox2.Text = booking.Surname;
textBox3.Text = booking.PESEL;
textBox4.Text = booking.Room;
You may refactor the repetitive statements about listbox refreshing..
change listBox1_SelectedIndexChanged method in that way that the selected listbox value is used as filter for your table, something like this:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml("D:\\data.xml");
//split selected item by spaces
var values = listBox1.SelectedItem.ToString().Split(' ');
var selectedRow = ds.Tables["Tabela"].AsEnumerable()
.Where
(r => r["Room"].ToString() == values[0] &&
r["Name"].ToString() == values[1] &&
r["Surname"].ToString() == values[2]).FirstOrDefault();
if (selectedRow != null)
{
textBox1.Text = selectedRow["Name"].ToString();
textBox2.Text = selectedRow["Surname"].ToString();
textBox3.Text = selectedRow["PESEL"].ToString();
textBox4.Text = selectedRow["Room"].ToString();
}
}

how to trigger an event when an item is selected from combobox in c#.net

string Sql_type = "select property_type_id,type_name from lk_tb_property_type";
OleDbCommand cmd_type = new OleDbCommand(Sql_type, con);
OleDbDataReader DR_two = cmd_type.ExecuteReader();
DataTable table_two = new DataTable();
table_two.Load(DR_two);
//begin adding line
DataRow row_two = table_two.NewRow();
row_two["type_name"] = "Select Poperty Name";
row_two["property_type_id"] = 0;
table_two.Rows.InsertAt(row_two, 0);
//end adding a line
combo_type.DataSource = table_two;
combo_type.DisplayMember = "type_name";
combo_type.ValueMember = "property_type_id";
combo_type.Text = "Select Poperty Name";
with this code i am fetching values for a combobox from database.now suppose my combobx is having 2 items named A and B..I have one more combobox...now what i want is that when user chooses item A from combobox the second combobox should display data related to item A when user chooses item B then data related to item B should be displayed...sohow to achieve this...??
you can fetch the data and bind it to combobox2 on SelectedIndexChanged event of combobox1
private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
{
var val = combobox1.SelectedValue;
// fetch data from database
// you need to set SQL parameter value form SelectedValue
combobox2.DataSource = ...; // set this value
combobox2.DisplayMember = .....; // set this value
combobox2.ValueMember = ....; // set this value
}
Please assign an event SelectedIndexChanged and AutoPostBack = true is this is a web Application in C#
In SelectedIndexChanged of combo box write your code. and make AutoPostBack = true of your combobox
You can do like these steps.
First, bind data to comboBox1 (I suppose that your first ComboBox named "comboBox1", and your form named "Form1"), please make sure that your SQL query command is correct for comboBox1
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string Sql_cust_name = "select customer_name from tb_customer";
OleDbCommand cmd_cust_name = new OleDbCommand(Sql_cust_name, con);
OleDbDataReader DR_cust_name = cmd_cust_name.ExecuteReader();
DataTable table_cust_name = new DataTable();
table_cust_name.Load(DR_cust_name);
DataRow row_cust_name = table_cust_name.NewRow();
row_cust_name["customer_name"] = "Select Customer Name";
table_cust_name.Rows.InsertAt(row_cust_name, 0);
combo_cust_name.DataSource = table_cust_name;
combo_cust_name.DisplayMember = "customer_name";
combo_cust_name.ValueMember = "customer_name";
combo_cust_name.Text = "Select Customer Name";
con.Close();
}
Next, bind data to comboBox2 (I suppose that your second ComboBox named "comboBox2"), you have to get comboBox1.SelectedValue whenever it is changed, this value will be used in the filtering for data in comboBox2, so you have to handle SelectedIndexChanged event for comboBox1, please make sure that you have this code somewhere in your project: this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
To bind data to comboBox2 (I suppose that your second ComboBox named "comboBox2"), you have to get comboBox1.SelectedValue whenever it is changed
private void combo_cust_name_SelectedIndexChanged(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string customerName = "";
if (combo_cust_name.SelectedValue.GetType() == typeof(DataRowView))
{
DataRowView selectedRow = (DataRowView)combo_cust_name.SelectedValue;
customerName = selectedRow["customer_name"].ToString();
}
else
{
customerName = combo_cust_name.SelectedValue.ToString();
}
string Sql2 = "SELECT customer_number FROM tb_customer WHERE customer_name = '" + customerName + "'";
OleDbCommand cmd_type = new OleDbCommand(Sql2, con);
OleDbDataReader DR_two = cmd_type.ExecuteReader();
DataTable table_two = new DataTable();
table_two.Load(DR_two);
DataRow row_two = table_two.NewRow();
row_two["customer_number"] = "Select Customer Number";
table_two.Rows.InsertAt(row_two, 0);
comboBox2.DataSource = table_two;
comboBox2.DisplayMember = "customer_number";
comboBox2.ValueMember = "customer_number";
comboBox2.Text = "Select Customer Number";
}
Please correct the SQL query command as you want, but don't forget to put a correct filter like my sample code above.

Get selected value from comboBox

I'm using C#, winforms.
Got a small problem. I've debugged as much as possible that leads me to believe the code I'm using is causing the problem.
Ok so I have a combo box that is filled with data from a query.
There are 2 columns "name", and "keycode". I display the name only using:
accCollection.DisplayMember = "name";
Then I use the following to get the keycode value that corresponds to the name.
string acct = accCollection.SelectedValue.ToString();
The problem I have is the keycode does NOT match the name. I though this may be my query so what I did was to display the query results in a data grid view JUST before I fill the comboBox. The data grid view displays the correct results which leads me to believe that I'm using the wrong code!
Hopefully it's a silly one line problem, if you guys want any more code let me know and I will edit this post.
UPDATE heres the code i forgot to mention, as you can see i already have assigned the data member
accCollection.DataSource = myTable;
accCollection.DisplayMember = "name";
accCollection.ValueMember = "keycode";
UPDATE:::: Ok some more info. the selected value should be 1557 which is the names account number. but i get 1855, which is a different account number. like i said the datatable is correct....this is why im sooooooo confused!
UPDATE:: heres some code so you can see how i update the combo box with the info!
SqlCommand accountFill = new SqlCommand("SELECT name, keycode FROM dbo.Customer", conn1);
SqlDataAdapter readacc = new SqlDataAdapter(accountFill);
DataTable dt = new DataTable();
readacc.Fill(dt);
dataGridView3.DataSource = dt;
conn1.Close();
accCollection.DataSource = dt;
accCollection.DisplayMember = "name";
accCollection.ValueMember = "keycode";
then i pass the following into my task that calls my other query.
private void button1_Click_1(object sender, EventArgs e)
{
checkBox1.Checked = true;
string acct = accCollection.SelectedValue.ToString();
Task t = new Task(() => GetsalesFigures(acct));
t.Start();
}
UPDATE:: just to show the data i get!
ok so after some help with debugging, ive used the follwing code to get these resuults.
var result = accCollection.SelectedValue;
if (result != null)
{
MessageBox.Show(result.ToString());
}
this = 1885 which is wrong
BUT when i do this.
DataRowView row = (DataRowView)accCollection.SelectedItem;
if (row != null)
{
MessageBox.Show(row[0] + " " + row[1]);
}
its shows the correct data, "melksham" "1557"
why is this?
You may use SelectedValue or SelectedItem property but also you have to check whether the returned value is null or not.
If you bind the DataTable then the SelectedItem property return DataRowView.
DataRowView row = (DataRowView)accCollection.SelectedItem;
if(row!=null)
{
MessageBox.Show(row[0] + " " + row[1]);
}
In case of SelectedValue,
var result = accCollection.SelectedValue;
if (result != null)
{
MessageBox.Show(result.ToString());
}
EDIT:
Code in Form_Load event:
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("A1", typeof(int));
dt.Columns.Add("A2");
dt.Rows.Add(1, "A");
dt.Rows.Add(2, "B");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "A2";
comboBox1.ValueMember = "A1";
}
Code in Click handler of Button:
var result = comboBox1.SelectedValue;
if (result != null)
{
MessageBox.Show(result.ToString());
}
DataRowView row = (DataRowView)comboBox1.SelectedItem;
if (row != null)
{
MessageBox.Show(row[0] + " " + row[1]);
}
Several Things:
DisplayMember property should be the name of the column to be displayed inside the combobox.
ValueMember property should be the name of the column which is the value of the item.
accCollection.DisplayMember = "name";
accCollection.ValueMember = "key";
If you want the value of the selected item you should use:
string acct = accCollection.SelectedValue.ToString();
Get the Display text as :
string acct = accCollection.SelectedText;
See this for details .
I have created a DataTable & i used to bind the dataTable to the combobox to display the title types and i wanted to get the title id which is in the datatable to a variable.
cmbTitle.DataSource=dataTable;
cmbTitle.DisplayMember="title_type";
cmbTitle.ValueMember="id";
then on the selection changed event of cmbtitle, i got the selected value member to a string and parsed in into an integer to save it back for the database as it is a foreign key.
private void cmb_title_SelectedIndexChanged(object sender, EventArgs e)
{
string userTitle = cmb_title.SelectedValue.ToString();
int.TryParse(userTitle, out this.userTitle);
MessageBox.Show(this.userTitle.ToString());
}

combobox items from the database

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)
{
....
}

Categories