Searching between two dropdown menu in window form Application - c#

I achieved search through one dropdown menu.
private void search_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM magzines where issue_number = '"+comboBox1.Text+"'";
SqlDataAdapter sda = new SqlDataAdapter(query , con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
}
}
please help me how i can search through two dropdown menu?

You should change to paramertised query to avoid SQL injection attacks, and not concatenate the SQL string as you're doing. To answer the question, add a second dropdown and use BETWEEN in the query...
string query = "SELECT * FROM magzines where issue_number BETWEEN '"+comboBox1.Text+"' AND '"+comboBox2.Text+"'";
Example using params...
using (SqlConnection conn = new SqlConnection(con))
{
string query = "SELECT * FROM magzines where issue_number BETWEEN '#comboOne' AND '#comboTwo'";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("comboOne", SqlDbType.VarChar).Value = comboBox1.Text;
cmd.Parameters.Add("comboTwo", SqlDbType.VarChar).Value = comboBox2.Text;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(table);
}
}

you can use BindingSource
BindingSource source1 = new BindingSource();
source1.DataSource = view1;
// Set the data source for the DataGridView.
datagridview1.DataSource = dt ;
//The Filter string can include Boolean expressions.
source1.Filter = "artist = 'Dave Matthews' OR cd = 'Tigerlily'";
for more visit http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.filter%28VS.90%29.aspx

Related

combobox Selected Text changed event not firing

This is my code. After adding data through DataSource, The SelectedIndexChanged event is not firing.
try
{
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
//comboBox1.Items.Clear();
comboBox1.ResetText();
Cn.Open();
SqlCommand Cd = new SqlCommand("Select Distinct Mobile From Client_Details Where Branch = '" + label2.Text + "'", Cn);
SqlDataReader da = Cd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
dt.Load(da);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
}
finally
{
Cn.Close();
Clear();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//Label CBSL = new Label();
//string CBSL = this.comboBox1.SelectedItem.ToString();
if (comboBox9.Text == "Client")
{
Update_Read_Client();
}
else if (comboBox9.Text == "Customer")
{
Update_Read();
}
}
It selects the first value again and again.
I had tried DropDownStye = DropDownList., But it become dormant. No values is added.
Any help to resolve my problem.
I'm not sure if you have "< Select >" item saved in your database. Also, when using DataTable it's easier to fill it using SqlDataAdapter. You should also use parameters instead of string concat when you're writing your query like this and using keyword closes your connection automatically when you're done using it. I'd write it like this probably:
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT DISTINCT Mobile
FROM Client_Details
WHERE Branch = #Branch";
cmd.Parameters.AddWithValue("#Branch", label2.Text);
try
{
var dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataRow row = dt.NewRow();
row["Mobile"] = "<Select>";
dt.Rows.InsertAt(row, 0);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
throw;
}
}

Must declare a scalar variable.?

I have to display bar chart using ajax extender tool. I have to display information on chart when I am selecting one value from drop down list. But it shows "Must declare a scalar variable" error. Please help me.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select Name from aTable";
DataTable dt = GetData(query);
ddlCountries.DataSource = dt;
ddlCountries.DataTextField = "Name";
ddlCountries.DataValueField = "Name";
ddlCountries.DataBind();
ddlCountries.Items.Insert(0, new ListItem("Select", ""));
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
string query = string.Format("select Debit, Credit, Year From aTable where Name=#Name", ddlCountries.SelectedItem.Value);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = y });
BarChart1.CategoriesAxis = string.Join(",", x);
BarChart1.ChartTitle = string.Format("{0} Order Distribution", ddlCountries.SelectedItem.Value);
if (x.Length > 3)
{
BarChart1.ChartWidth = (x.Length * 100).ToString();
}
BarChart1.Visible = ddlCountries.SelectedItem.Value != "";
}
In this line
string query = string.Format(#"select Debit, Credit, Year
From aTable where Name=#Name",
ddlCountries.SelectedItem.Value);
you have a parameter placeholder #Name but you don't add the required parameter to the SqlCommand that executes the sql. This produces the error that you see.
(By The way, string.Format requires the placeholder in the form {0}, but also if you fix that problem it is still wrong because you leave open the door to Sql Injection)
Fixing it requires a change in your GetData function.
You need to add an (optional) parameter array as another argument
private DataTable GetData(string query, SqlParameter[] prms = null)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
if(prms != null)
cmd.Parameters.AddRange(prms);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
And now, when you call that method, you could write
string query = "select Debit, Credit, [Year] From aTable where Name=#Name";
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#Name", SqlDbType.NVarChar).Value =
ddlCountries.SelectedItem.Value.ToString());
DataTable dt = GetData(query, prms);
Notice also that I have put the field Year between square brackets. Year is the name of a T-SQL Function and you should use this trick to avoid to confuse the SQL Parser

How to check weather my comboobx value is already inserted and if its inserted already in database the perticular value wont be visible in the list

I have a strange problem,
I'm working with win-form which is coding in c#..and sql server
In a form I have a Combo-box which is collected data by the database(say 1).
and later I have to Insert that particular value/member details into another database(say 2)
Here My problem raises,,Once My combo-box any value is inserted into 2nd database,that particular value/member should not visible in the combo-box for the next time on the same day..
Of course Here I'm using datetimepicker..
Here I'm using following code...and Of-course it is wrong..Please Help me
SqlCommand cmd1 = new SqlCommand("select employee_id,Empployee_Name,date from dailyattendance", cn);
SqlDataReader sdr;
DataTable dt = new DataTable();
sdr = cmd1.ExecuteReader();
if (sdr.Read())
{
string employeeid = (string)sdr["employee_id"];
string employeename = (string)sdr["Empployee_Name"];
string date = (string)sdr["date"];
try
{
//cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name from Employee_Details", cn);
SqlDataReader sdr1;
DataTable dt1=new DataTable();
sdr1 = cmd.ExecuteReader();
dt1.Load(sdr1);
if (sdr1.Read())
{
string date1=dateTimePicker1.Value.ToString("dd/MM/yyyy");
if ()//here the main problem
{
string employeeid1 = (string)sdr1["employee_id"];
string employeename1 = (string)sdr1["employee_name"];
comboBox1.DisplayMember = employeeid1;
comboBox1.DisplayMember = employeename1;
comboBox1.DataSource=dt1;
cn.Close();
}
}
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
try
{
string dtp = dateTimePicker1.Value.ToString("dd/MM/yyyy");
string query = "select employee_id,employee_name,image_of_employee,image_path from Employee_Details where employee_id not in (select employee_id from dailyattendance where date = '" + dtp + "')";//Here added a new query which is working
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dtr);
foreach (DataRow row in dt.Rows)
{
var name = (string)row["employee_name"];
row["employee_name"] = name.Trim();
}
comboBox1.ValueMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
listBox1.ValueMember = "employee_id";
listBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
listBox1.DataSource = dt;
comboBox1.SelectedItem = null;
listBox1.SelectedItem = null;
cn.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
Simply at query added some workable logic

column count property cannot be set on a databound datagridview control c#

In My form I have a DataGridView. and controls for input and output data. while displaying data in the gird view. I am calling BindGrid in two occasions. One while formload and other is After adding a new record.
public formAccounts()
{
InitializeComponent();
BindGrid();
}
private void BindGrid()
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= G:\Sanjeev\TESTDB\DB.mdb;Jet OLEDB:Database Password=Test123; Jet OLEDB:Engine Type=5";
conn.Open();
string constring = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=G:\Sanjeev\TESTDB\DB.mdb;Jet OLEDB:Database Password=Test123; Jet OLEDB:Engine Type=5";
using (OleDbConnection con = new OleDbConnection(constring))
{
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM tblAccounts", con))
{
cmd.CommandType = CommandType.Text;
using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Set AutoGenerateColumns False
dtGrdAccounts.AutoGenerateColumns = false;
//Set Columns Count
***dtGrdAccounts.ColumnCount = 3;***
//Add Columns
dtGrdAccounts.Columns[0].Name = "AccountID";
dtGrdAccounts.Columns[0].HeaderText = "Id";
dtGrdAccounts.Columns[0].DataPropertyName = "AccID";
dtGrdAccounts.Columns[1].HeaderText = "Account name";
dtGrdAccounts.Columns[1].Name = "Account name";
dtGrdAccounts.Columns[1].DataPropertyName = "AccName";
dtGrdAccounts.Columns[2].Name = "AccountNumber";
dtGrdAccounts.Columns[2].HeaderText = "Account number";
dtGrdAccounts.Columns[2].DataPropertyName = "AccNumber";
dtGrdAccounts.DataSource = dt;
}
}
}
}
}
If I remove the line dtGrdAccounts.ColumnCount = 3; I am getting below error.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
After adding the a new record , On button save I am calling BindGrid() method to get the record in the GridiView.
string cmdText = "prAddAccounts";
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("AccName", txtAccName.Text.ToString());
//..... other parameters to insert record .....
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
cmd.CommandType = CommandType.StoredProcedure;
OleDbDataReader reader = cmd.ExecuteReader();
BindGrid();
The issue is when you call the BindGrid() again you have to clear it first:
string cmdText = "prAddAccounts";
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("AccName", txtAccName.Text.ToString());
//..... other parameters to insert record .....
//Clear the binding.
dtGrdAccounts.DataSource = null;
//Bind the new data.
BindGrid();
if you are calling datagridview colum design code more than once then
before setting column property you have to make Gridview data source to null
as shown below
dataGridView1.DataSource = null;
using (DataTable dt = new DataTable())
{
//add this line of code
dtGrdAccounts.DataSource = null;
sda.Fill(dt);
//Set AutoGenerateColumns False
dtGrdAccounts.AutoGenerateColumns = false;
//Set Columns Count
***dtGrdAccounts.ColumnCount = 3;***
//Add Columns
dtGrdAccounts.Columns[0].Name = "AccountID";
dtGrdAccounts.Columns[0].HeaderText = "Id";
dtGrdAccounts.Columns[0].DataPropertyName = "AccID";
dtGrdAccounts.Columns[1].HeaderText = "Account name";
dtGrdAccounts.Columns[1].Name = "Account name";
dtGrdAccounts.Columns[1].DataPropertyName = "AccName";
dtGrdAccounts.Columns[2].Name = "AccountNumber";
dtGrdAccounts.Columns[2].HeaderText = "Account number";
dtGrdAccounts.Columns[2].DataPropertyName = "AccNumber";
dtGrdAccounts.DataSource = dt;
}

How do i bind data source to a ComboBox?

So i currently have two combo boxes. One Being Manufacture the other being model. My sql query looks like this "Select Distinct Model From sheet1 where (Manufacture =#Manufacture)" this works when i execute it and if i were to fill a datagridtable. But if i try to place this into a combobox i get System.data.d...... etc for my selections. How can i just have it show the values instead of all this. What am i doing wrong?
private void ManuComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string manu = comboBox3.Text;
string conStr = "Data Source=CA-INVDEV\\RISEDB01;Initial Catalog=RISEDB01; Integrated Security=True";
string sqlcmd = "SELECT DISTINCT Model FROM Sheet1 WHERE (Manufacture =#Manufacture)";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Close();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource3.DataSource = table;
ModelComboBox.DataSource = bindingSource3;
}
}
}
Can you give this a try?
using (SqlConnection conn = new SqlConnection(conStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
IList<string> modelList = new List<string>()
while (dr.Read())
{
modelList.add(dr[0].ToString());
}
ModelComboBox.DataSource = modelList;
}
If you have set the display member like:
ModelComboBox.DataSource = bindingSource3;
ModelComboBox.DisplayMember = "ColumnName";
And it still shows funny values, what are the values that it shows exactly?
Note, in a toolstrip it looks like you may have to also do:
ModelComboBox.BindingContext = this.BindingContext;
here is a reference
Try adding
ComboBox1.ItemsSource = bindingSource3
if this is your answer then mark it as answer

Categories

Resources