Same SelectedIndexChanged function for 2 comboboxes c# - c#

I made a same event for 2 comboboxes to populate my input controls so the user can see what they would be deleting or updating. When I made separate events it worked but upon making the same event it does not work. What conditions should i put in the if-statements
on this if condition the error i get id "Index was outside the bounds of the array"
private void BoardComboBo(object sender, EventArgs e)
{
if (comboBox12.SelectedIndex!=0)//error is here
{
con.Open();
cmd = new SqlCommand("Select * from Users where user_Id='" + comboBox12.Text + "';", con);
SqlDataReader DR1 = cmd.ExecuteReader();
if (DR1.Read())
{
//code to fill textboxes
}
con.Close();
}
if(comboBox1.SelectedIndex!=0)//error is here
{
//to split combobox values
string selectedvalue = comboBox1.Text;
split = selectedvalue.Split();
//add values on fields
con.Open();
cmd = new SqlCommand("Select * from Users where firstName='" + split[0] + "' and lastName='" + split[1] + "';", con);
SqlDataReader DR1 = cmd.ExecuteReader();
if (DR1.Read())
{
//code to fill textboxes
}
con.Close();
}
}
I changed the second if condition too:
if (comboBox12.Text!=" ")// this works
{
//to split combobox values
string selectedvalue = comboBox1.Text;
split = selectedvalue.Split();
//add values on fields
con.Open();
cmd = new SqlCommand("Select * from Users where firstName='" + split[0] + "' and lastName='" + split[1] + "';", con);
SqlDataReader DR1 = cmd.ExecuteReader();
if (DR1.Read())
{
//code to fill textboxes
}
con.Close();
}
I am now getting the same error above when i try to select by user_Id

In the method signature, the sender object is the one that's triggering the event, so we can just cast it to a ComboBox and check if it's one that we care about:
private void BoardComboBo(object sender, EventArgs e)
{
var comboBox = sender as ComboBox;
if (comboBox == comboBox1)
{
// comboBox1 code here
}
else if (comboBox == comboBox12)
{
// comboBox12 code here
}
}
However at this point, you may as well have two separate events. Since there is no significant duplicated code that's specific to the ComboBoxes, refactoring them into one event only makes the code more cumbersome.
Regarding the "Index was outside the bounds of the array" error, the only place you reference an index is when you split the Text property of comboBox1. Most likely, the Text does not have any whitespace in it, so Split is returning a single-item array. Then the problem is when you try to access an index that doesn't exist here:
split[1] // Here you're attempting to access an index that doesn't exist
To fix this issue, check the Length of the array before accessing indexes that may not exist, maybe something like:
// Set the last name to an empty string if it didn't exist
var lastName = split.Length > 1 ? split[1] : string.Empty;
Note that you should be using SQL command parameters to build the query string. The way you're doing it is vulnerable to SQL injection.
Also, as #Streamline mentioned, your original code has two if blocks instead of an if / else if. This means that both the if conditions will be evaluated regardless of which control triggered the event. It also means that if both ComboBoxes have a non-zero SelectedIndex, then both the if block bodies will run. This may be a cause for the error in the code from your question, and is not likely the intended behavior.
Finally, as #OlivierJacot-Descombes mentioned, if no item is selected then SelectedIndex will be -1, not 0. This means that when you check for comboBox1.SelectedIndex!=0, not only are you ignoring the value in the first (0) position, but if no value is selected, then it will pass this condition (because the value in that case is -1).

Related

Getting Data from the existing data #c.net

I have used this code to display the employee's first name and last name from the provided database when an employee id number is typed into the text box and the “Find” button is clicked. But I will also need Previous and Next Button to display previous and next records respectively in textbox as well. Is there a method like MovePrevious and MoveNext sth to get it?
Here is my code :
private void button1_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\CCEMPLOYEE.mdb";
OleDbConnection con = new OleDbConnection(constr);
{
using (OleDbCommand cmd = new OleDbCommand("SELECT emp_fname, emp_lname, emp_mi FROM Employee WHERE emp_id =#ID "))
{
if (idText.Text != "")
{
cmd.Parameters.AddWithValue("#ID", int.Parse(idText.Text));
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (OleDbDataReader sdr = cmd.ExecuteReader())
{
try
{
sdr.Read();
fnameText.Text = sdr["emp_fname"].ToString();
lnameText.Text = sdr["emp_lname"].ToString();
miText.Text = sdr["emp_mi"].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
else
{
MessageBox.Show("You did not enter any ID", "Enter the ID ",
MessageBoxButtons.OK);
}
con.Close();
}
}
}
You won't be able to go Next or Previous in your provided code because you only have one record in your recordset.
You will also have the problem that you haven't specified the basis for what "Previous" and "Next" mean, the framework has no idea that you mean next by emp_id (or do you mean next by alphabetical surname?)
I would suggest your Prev and Next buttons need to be aware of what "this" record is, and use that as a parameter to run a similar piece of code when they are clicked. You could add an int property to your class, have the Find button store the emp_id into that property, and then have the Next and Prev buttons call almost identical code except with the SQL adjusted to something like "SELECT TOP 1 emp_fname, emp_lname, emp_mi FROM Employee WHERE emp_id > #ID ORDER BY emp_id ASC" (note I don't have anything on me to test this at the moment, you might need to sort DESC).
The reason I've suggested TOP 1, > and ORDER By is I don't know if you have a guarantee that you have sequential emp_id - obviously if you know they're sequential and can guarantee that always you could just go "SELECT... WHERE emp_id = #ID-1" for Prev...
This answer is academic, not practical, I don't suggest this is a good solution to a production scenario - it's an answer to your question.

Update command dont work ms access c#

I got a gridview which is connected to a datasource getting values from there.I created a selectedindexchanged function to work when select is clicked.it shows ID , orderID,From,To and Price values and opens panel which has 4 textbox's and a dropdownlist if user wants to change those values.Everything is fine until here.When user changes some values and clicks submit nothing changes in database.I got the values using id ; " string id = orderGrid.SelectedRow.Cells[1].Text; "
here is my submit button code ;
protected void submitButton_Click(object sender, EventArgs e)
{
string id = orderGrid.SelectedRow.Cells[1].Text;
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("db.mdb") + ";Persist Security Info=False");
string query = "update ordersTable set orderID=#testID,fromLocation=#from,toLocation=#to,price=#price WHERE ID = #id ";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#testID", orderBox.Text);
cmd.Parameters.AddWithValue("#from", fromText.Text);
cmd.Parameters.AddWithValue("#to", toList.SelectedItem.Text);
cmd.Parameters.AddWithValue("#price", priceBox.Text);
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Edit Complete !");
}
catch (Exception ex)
{
Response.Write("Error : " + ex);
}
orderGrid.DataBind();
}
id string works perfectly fine in my selectedindexchanged function.
In OleDb parameters are recognized by their position not by their name.
Your parameter placeholder #ID is the last one in the query, but you add it as the first one in the collection.
This result in your WHERE condition to be totally wrong
(you search for a record whose ID is equal to the content of the priceBox)
Just move the insert of the ID as last parameter
cmd.Parameters.AddWithValue("#testID", orderBox.Text);
cmd.Parameters.AddWithValue("#from", fromText.Text);
cmd.Parameters.AddWithValue("#to", toList.SelectedItem.Text);
cmd.Parameters.AddWithValue("#price", priceBox.Text);
cmd.Parameters.AddWithValue("#id", id);
This is the primary problem, but I can see another one caused by your use of AddWithValue. This is an handy shortcut, but sometime it make you pay for it.
In your case, you pass to the #price parameter a string and, if your price field is a decimal (as it should be) then the database engine will attempt a conversion from a string to a decimal and if the decimal separator is not the same you end with a wrong value in the database. Better check the value in the priceBox and convert it yourself to a decimal.
See Can we stop to use AddWithValue already?

Save listbox items in database after ordering

I have an asp.net page with two listboxes and a save button. The user needs to transfer items from listbox1 to listbox2 according to his order I mean that user can choose witch item come in the first place and which come next.
After that my system suggest the results (most commonly) that achieve the ordered items, I hope you understand
I did the transfer method between the two listboxes and it work good. But I'm stuck in the save method, it can save the items after being in listbox2 but not in the same order of transferring (user order).
Here is my code for save button:
protected void Button1_Click(object sender, EventArgs e)
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
string str;
OracleCommand com;
OracleConnection con = new OracleConnection(strConnString);
try
{
con.Open();
for (int i = 0; i < ListBox2.Items.Count; i++)
{
str = "insert into Criteria values('" + ListBox2.Items[i].ToString() + "')";
com = new OracleCommand(str, con);
com.ExecuteNonQuery();
}
LabOut.Visible = true;
LabOut.Text = "Upload succesful!";
con.Close();
//Response.Write("Inserted");
}
catch (Exception)
{
LabOut.Visible = true;
LabOut.Text = "Upload failed!";
}
finally
{
con.Close();
con.Dispose();
}
}
The problem here is that database tables do not inherently have a concept of order. Retrieving rows from a table never guarantees an order unless you use a order by clause.
You should add an additional column to your table (named, for example, "Sequence" or "Order"). It can be an int or some other sortable value. You would then need to modify your insert statement:
str = "insert into Criteria(ItemValue, Sequence) values('" + ListBox2.Items[i].ToString() + "'," + i.ToString() + ")";
and retrieve the list using
str = "Select ItemValue from Criteria order by Sequence"
#fifo follow me
1st add a column in your database say it is SeqNo.
Then save your data with that. I mean generate SeqNo. for each listbox2 item and save it.
When you will fetch data from database into lintbox2 then use sql/linq ORDER BY on SeqNo. column and display them on which Order that you were saved. Simple.. :)

How to add user defined row into a datatable?

I have datagridview which is filled with values from DB when button clicked.
All these happen based on a condition from radiobutton.
Now i need to add some extra row (default value) into the datatable, each time these conditions apply.
When button clicked and radiobutton condition apply,these codes will happen.
if (radioButton1.Checked == true)
{
string query = "SELECT type,priceS FROM service WHERE type='" + button5.Text + "'";
MySqlCommand cmd = new MySqlCommand(query, con);
dt.SelectCommand = cmd;
}dt.Fill(tt);
dataGridView1.DataSource = tt;
The query will return
string =type and int=priceS
from DB, i just need add string "S" with the "type" value
For example: if type = Style then in the datatable it be should "Style(S)"
any help is appreciated.
Instead of using Datatables i solved it in the MySQL Query itself
Query="Select Concat(type,'S'),price from service"
This will add the string S with that of the type's value.

Listing a number twice in a list box when pulling data from a database using the and key word in the sql statment in C#

Sorry for the large heading, I don't know what is going on with my code. I am pulling all serial numbers for a given work order number and status code and populating a list box with the results. My issue is, my code is pulling the number but listing it twice in the list box control. I am using a postgres database. Here is my code.
private void Get_Serial_Numbers()
{
NpgsqlConnection conn = Connection.getConnection();
try
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("select product_serial_number from master_product where product_wo_number = :WorkOrder and status = :Status;", conn);
cmd.Parameters.Add(new NpgsqlParameter("WorkOrder", IdStorage.WorkOrderNumber));
cmd.Parameters.Add(new NpgsqlParameter("Status", 128));
NpgsqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
object serialNumber = dr["product_serial_number"];
lstProductsInWO.Items.Add(serialNumber.ToString());
}
if (lstProductsInWO.Items.Count == 0)
{
lstProductsInWO.Items.Add("No Data");
lblSerialInWO.Text = "Products in WO 0";
}
else
{
ProductTotal = lstProductsInWO.Items.Count;
lblSerialInWO.Text = "Products in WO " + ProductTotal.ToString();
}
dr.Close();
cmd.Dispose();
}
There are two possilities:
You accidently call the method Get_Serial_Numbers() twice in some event handlers - check it by debugging to make sure that the code runs only once.
You get the items twice from the table. Verify what the query returns (under the debugger) or running it manually against the database.

Categories

Resources