Combobox items based on input from two other comboboxes - c#

Hi I have an access table called equipment table and a win form with multiple comboboxes the first three work but they are getting distinct values from the Access table. The third however is receiving input from the comboboxes Manufacturer_cmbBx and Type_cmbBx which work. I have used the same code for all the comboboxes and only the Select query has changed. The Diagnostic tool in VS shows that the right values are being passed into the Select query. yet the combobox remains empty. I have called for the combobox to be changed on the SelectedValueChanged event of the combobox Type_cmbBx
private void LoadModel_cmbBx()
{
string strCon = Properties.Settings.Default.Database2ConnectionString;
using (OleDbConnection conn = new OleDbConnection(strCon))
{
try
{
string strSql = "Select Model from EquipmentTable where [Manufacturer] = '" + Manufacturer_cmbBx.Text + "' and [Type] = '" + Type_cmbBx.Text + "'";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
DataSet ds = new DataSet();
adapter.Fill(ds);
Model_cmbBx.DataSource = ds.Tables[0];
Model_cmbBx.ValueMember = "Model";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Using The Dataset Viewer in VS I could see that only the Model column was in there so I changed my statement to
"Select DISTINCT * from EquipmentTable where Type = '" + Type_cmbBx.Text + "' and Manufacturer = '"+ Manufacturer_cmbBx + "'";
This still didn't work but
"Select DISTINCT * from EquipmentTable where Type = '" + Type_cmbBx.Text + "'";
Works as does
string strSql = "Select DISTINCT * from EquipmentTable where Manufacturer = '" + Manufacturer_cmbBx + "'";
only when I try to add a second combobox does the Dataset remain empty. Any thoughts as to why this is?

Related

Conversion failed when converting the varchar value 'System.Windows.Forms.ComboBox+ObjectCollection' to data type int

I began to show my DataGrid on a form is created I would like when I course id, rollno. or enroll no but when I execute this code than show the following problem:
Conversion failed when converting the varchar value 'System.Windows.Forms.ComboBox+ObjectCollection' to data type int
private void btnSubmit_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand(
"select COURSE_Id, ROLL_NO, ENROLL_NO, Sub_P_CODE, STUDENT_NA, th_a_o, th_b_o, th_c_o " +
"FROM annual_2018 " +
"where COURSE_ID = '" + course_id.Items.ToString() + "' " +
"and (ROLL_NO = '" + txtRoll.Text + "' OR ENROLL_NO = '" + TxtEnroll.Text + "')",
con);
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
Enroll_no.DataSource = dt;
con.Close();
}
You have passed the whole ComboBox, you need to specify the SelectedValue of your ComboBox. Your COURSE_ID column in the table is an int datatype and that is what you need to pass it. Also you should always use parameterized queries to avoid SQL Injection. Your code should be something like this:
int selectedValue = Convert.ToInt32(course_id.SelectedValue.ToString());
cmd = new SqlCommand("select COURSE_Id, ROLL_NO, ENROLL_NO, Sub_P_CODE, STUDENT_NA," +
" th_a_o, th_b_o, th_c_o FROM annual_2018 where COURSE_ID = #courseId" +
" and (ROLL_NO = #ROLL_NO OR ENROLL_NO = #ENROLL_NO)", con);
command.Parameters.AddWithValue("#courseId", selectedValue );
//Other parameters
Although specify the type directly and use the Value property is more better than AddWithValue. See this Can we stop using AddWithValue() already?
cmd.Parameters.Add("#courseId", SqlDbType.Int).Value = selectedValue;

How to disregard empty textbox or combobox in SQL SELECT?

I have a C# form that have a 6 filters (5 combobox, and 1 textbox) that the user can use to perform a search. The problem is that the user can leave some as blank or to use it all. To have a filtered search I used AND when doing a SELECT query, but the problem is it will return a blank or empty search when some of the filters is/are blank. If I will make each condition a query, I will have around 700 and so query. So I have search the closet, I think, scenario in this link
Ignore empty textboxes while searching in database
using (SqlConnection conn = new SqlConnection(#"Data Source=(local);
Initial Catalog=inventory;
Integrated Security=True"))
{
conn.Open();
string query = "SELECT * FROM [dbo].[product] WHERE IsDeleted = '0'";
using (SqlCommand scmd = new SqlCommand())
{
if (!string.IsNullOrEmpty(cmbItem.Text))
{
query += " AND Item Like #Item";
scmd.Parameters.Add("#Item", SqlDbType.VarChar).Value = "%" + item + "%";
}
}
if (!string.IsNullOrEmpty(cmbBrand.Text))
{
query += " AND Brand Like #Brand";
scmd.Parameters.Add("#Brand", SqlDbType.VarChar).Value = "%" + brand + "%";
}
//...additional query
}
scmd.CommandText = query;
scmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(scmd))
{
dataGridView1.Refresh();
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
conn.Close();
}
And when performing the search, it is having an error like this;
'Invalid column name 'IsNull'.'
My original query goes something like this. But this will select nothing if one of the where condition is blank/empty.
SELECT * FROM [dbo].[product] WHERE Item = '" + item + "'
AND Brand = '" + brand + "'
AND Description = '" +desc + "'
AND Manufacturer = '" + manu + "'
AND Car = '" + car + "'
AND Year = '" + year + "'
If I use OR instead of AND. It will select something like this.
OR Statement
OR Statement
Below are the images for an ideal search.
Image for ideal selection
Image for ideal selection
Solved, by changing IsDeleted='0' to 1=1
string query = #"SELECT * FROM[dbo].[product] WHERE 1=1";
you can use store procedure and set parameter to default value
sample:
create proc sptest
#Fname nvarchar(50),
#Lname nvarchar(50),
#NCode nvarchar(12),
#UserType int
as
SELECT DISTINCT PersonID,
FName,
LName,
NationalID,
UserType
FROM Persons
WHERE
(FName LIKE('%' + #Fname + '%') OR (#Fname = ''))
AND (LName LIKE('%' + #Lname + '%') OR (#Lname = ''))
AND ((NCode = #NCode) OR (#NCode = ''))
AND ((UserType = #UserType) OR (#UserType = 0))
when textbox is empty or dropdownlists not is selected, get all record
Your original if/and conditions should work, but what you might be running into is a false resolution of the table COLUMN vs the PARAMETER. Since you have the example of
Item like #Item
if there is no actual parameter Item, SQL is implying to use its own value. For these types of queries, I try to prefix the parameter name to match. Change to
Item like #parmItem
and obviously change your parameter name string to match the "#parmItem" reference. This way there is no ambiguity in what value the SQL engine is looking for.

SqlCommand doesn't UPDATE and DELETE database when used in ASP.NET

I am having trouble with UPDATE and DELETE data in database when working with ASP.NET web form, the code work well with Windows form so I don't know what I did wrong. The code is suppose to update the Gridview with new edited data but when I click edit button, nothing happen to the gridview as well as the datatable.
This is just an exercise that there is no security requirement so I just want to know how to make it work first.
protected void Edit_btn_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
command.CommandText = ("UPDATE WareHouse SET [Name] = '" + Name_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Number] = '" + Number_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Storage] = '" + Storage_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Shelf] = '" + Shelf_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Brand] = '" + Brand_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM WareHouse", sqlCon);
DataTable ds = new DataTable();
ad.Fill(ds); // Fill t with data from Adapter a
GridView1.DataSource = ds; // Get data from Source t
GridView1.DataBind();
}
and for delete data
protected void Remove_btn_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
command.CommandText = "DELETE FROM WareHouse WHERE [Name] = '" + Name_Field.Text + "' AND [Number] = '" + selectedNumber + "' AND [Storage] = '" + selectedStorage + "' AND [Shelf] = '" + selectedShelf + "' AND [Brand] = '" + selectedBrand + "'";
command.ExecuteNonQuery();
clear();
showData();
}
Aside these 2 function, there are other two that do adding and searching from database which also use SqlCommand and they work fine without problem. Is there any problem with my query?
Storage, Shelf and Brand wouldn't be updated since you are updating [Number] to have the value of Number_Field.Text and then comparing with selectedName in where clause.
It will help you a great deal to put all this SQL code in SP with parameters and call it from ASP.Net code.
Ok.I also faced this issue back when I was learning ASP.NET.
But i had a little different env.
I had a datagrid to play with and any updates in datagrid content should reflect back in DB table upon clicking update button.
So I had below query to populate the grid.
Try
Dim UpperCase As String = UCase(HostnameTextBox.Text)
Dim sql As String = "select * from HOST_DETAILS where upper(HOSTNAME) like '%" + UpperCase + "%'"
da = New OracleDataAdapter(sql, conn)
ds.Clear()
da.Fill(ds, "TEST")
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
And the below one to update the table on the Update button click.
conn.Open()
Try
Dim ocb As New OracleCommandBuilder
ocb = New OracleCommandBuilder(da)
da.Update(ds, "TEST")
MessageBox.Show("Information Updated")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
conn.Close()
Also make sure DataAdapter da is global and is defined right after public class so it can be accessed from both.
Dim da As New OracleDataAdapter
Hope this helps.

C# query with 3 AND conditions

I have 3 combobox that take there information from MS Access database. I want to select data from database according to the values of the combo boxes.
I wrote this query:
string query = "select * from products where category='" + comboBox1.Text + "' and subcategory='" + comboBox2.Text + "' and size='" + comboBox3.Text + "'";
But it gives me the following exception:
IErrorInfo.GetDescription failed with E_FAIL(0x80004005).
Can you help me?
Full code:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from products where category='" + comboBox1.Text +
"' and subcategory='" + comboBox2.Text + "' and size='" + comboBox3.Text + "'";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
I'm guessing since size is a reserved word in MS Access, it is throwing that error.
See this link for list of reserved words in Access.
Try changing the column name. Also, try to use parameterized query to prevent sql injection.
See this answer on how to use parameterized query in Access.

Insert multiple value from one column attributes to another

I have this assignation function where the admin can assign a police ID to a selected memberreportID. Firstly, the admin will select the case, select the location and choose the number of officers needed for this case. For example if the admin chose 2 officers, it would then display 2 dropdownlist all binded to list down the policeID available.
protected void ddllocation_SelectedIndexChanged(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
ddlpid1.Items.Clear();
ddlpid1.DataSource = ds2;
ddlpid1.DataTextField = "policeid";
ddlpid1.DataValueField = "policeid";
ddlpid1.DataBind();
ddlpid1.Items.Insert(0, new ListItem("Police ID", ""));
ddlpid1.SelectedIndex = 0;
ddlpid2.Items.Clear();
ddlpid2.DataSource = ds2;
ddlpid2.DataTextField = "policeid";
ddlpid2.DataValueField = "policeid";
ddlpid2.DataBind();
ddlpid2.Items.Insert(0, new ListItem("Police ID", ""));
ddlpid2.SelectedIndex = 0;
}
}
The first SQL command is how i insert them into the assignto column of the selected memberreportID in my database. I'm inserting both policeID i have assigned into the same column, assignto.
protected void btnAssign_Click1(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
String assign = ddlpid1.SelectedValue + ", " + ddlpid2.SelectedValue + ";
connAdd.Open();
var sql = "Update MemberReport Set assignto ='" + assign + "' where memberreportID='" + lbmemberreportid.Text + "'";
using (var cmdAdd = new SqlCommand(sql, connAdd))
{
cmdAdd.ExecuteNonQuery();
}
sql = "Update PoliceAccount Set handle ='" + assign + "' where policeid ='" + ddlpid1.SelectedValue + "' OR '" + ddlpid2.SelectedValue + "'";
using (var cmdAdd = new SqlCommand(sql, connAdd))
{
cmdAdd.ExecuteNonQuery();
}
connAdd.Close();
}
}
However i'm also trying to input this policeID into a table called policeaccount by including the 2nd sql command. This policeaccount has a column called handle which is suppose to show the memberreportID he is handling at the moment. I'm trying to let each policeID's account to receive the selected memberreportID into their handle column by using the OR function. I'm pretty sure there's a OR function for sql syntax. But when i tried to insert i got this error instead
An expression of non-boolean type specified in a context where a condition is expected, near ''.
it should be as below
sql = "Update PoliceAccount Set handle ='" + assign + "' where policeid ='" + ddlpid1.SelectedValue + "' OR policeid = '" + ddlpid2.SelectedValue + "'";
Syntax is
UPDATE tblName Set col1 ='value'
WHERE col2 ='value2'
OR col2 ='value3'

Categories