retrieve the data using monthcalendar control - c#

private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= C:\\Users\\JAY\\Desktop\\Employee.mdb");
OleDbCommand cmd = new OleDbCommand("select * from Emp_Details WHERE DOB="+ monthCalendar1.SelectionRange.Start.ToShortDateString() +"", con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Emp_Details");
txtEmployeeNo.Text = ds.Tables[0].Rows[0][0].ToString();
txtName.Text = ds.Tables[0].Rows[0][1].ToString();
txtAddress.Text = ds.Tables[0].Rows[0][2].ToString();
comboBox1.Text = ds.Tables[0].Rows[0][3].ToString();
txtMobNo.Text = ds.Tables[0].Rows[0][4].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Basically i want to retrieve the data through monthcaledar control...but
when i click to date of monthcalendar control i got exception there is no row at position 0

Don't use inline parameters, you can use Parameterized query as below
using (var con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= C:\Users\JAY\Desktop\Employee.mdb"))
using (var cmd = new OleDbCommand("select * from Emp_Details WHERE DOB= ?", con))
{
cmd.Parameters.AddWithValue("#P1", monthCalendar1.SelectionRange.Start);
using (var da = new OleDbDataAdapter(cmd))
{
da.Fill(ds, "Emp_Details");
if (ds.Tables["Emp_Details"] !=null && ds.Tables["Emp_Details"].Rows.Count>0)
{
DataRow dr = ds.Tables["Emp_Details"].Rows[0];
txtEmployeeNo.Text = dr[0].ToString();
txtName.Text = dr[1].ToString();
txtAddress.Text = dr[2].ToString();
comboBox1.Text = dr[3].ToString();
txtMobNo.Text = dr[4].ToString();
}
}
}

Related

C# multi valued combo box value to SQL Server database

private void filljobid()
{
try
{
string jobid = "";
int newjobid, oldjobid;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("SELECT MAX(job_id) FROM job", con);
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
jobid = reader[0].ToString();
}
oldjobid = int.Parse(jobid.ToString());
newjobid = oldjobid + 1;
jobidtextbox.Text = newjobid.ToString();
}
catch (Exception)
{
MessageBox.Show("Error while connecting");
}
}
private void fillcustomercombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT customer_id,(first_name + ' ' + last_name + ' - ' + contact) AS CUSTOMERNAME FROM customer", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
customeridcombobox.DataSource = ds.Tables[0];
customeridcombobox.DisplayMember = "CUSTOMERNAME";
customeridcombobox.ValueMember = "customer_id";
cmd.ExecuteReader();
con.Close();
// CODE FOR DISPLAYING multiple values in another way, but not sure how to retrieve data from this function
// for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
// {
// customeridcombobox.Items.Add(ds.Tables[0].Rows[i][0] + " - " + ds.Tables[0].Rows[i][1] + " " + ds.Tables[0].Rows[i][2]);
// }
}
private void filldepotcombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT depot_id,(branch_name + ' - ' + region_name + ' - ' + location) AS DEPOTNAME FROM depot", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
depotidcombobox.DataSource = ds.Tables[0];
depotidcombobox.DisplayMember = "DEPOTNAME";
depotidcombobox.ValueMember = "depot_id";
cmd.ExecuteReader();
con.Close();
}
private void filljobtypecombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT job_type FROM jobtype", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
jobtypecombobox.DisplayMember = "job_type";
jobtypecombobox.ValueMember = "job_type";
jobtypecombobox.DataSource = ds.Tables[0];
cmd.ExecuteReader();
con.Close();
}
private void loadingcomboboxesdata_Load(object sender, EventArgs e)
{
fillcustomercombox();
filljobid();
filldepotcombox();
filljobtypecombox();
}
private void addnewjobbutton_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMoversDB;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into job (start_location, end_location, depot_id, job_type, customer_id,) values ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "','" + depotidcombobox.Text + "','" + jobtypecombobox.Text + "','" + customeridcombobox.Text + "')";
cmd.ExecuteReader();
con.Close();
MessageBox.Show("Added new job");
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
What I'm trying to achieve is basically take the users selected value which is displayed in the combo box which is valuemember and then insert it into the database. Right now I get the error when I try to insert the data into the database. When I do the combo box with a single value it works fine but it doesn't work when I do it with multiple values.
Could someone close this question. I managed to solve my own question. I dont know if this solution is considered good but here you go.
private void addnewjobbutton_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO job(start_location, end_location, depot_id, job_type, customer_id) VALUES ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "',#3,#4, #5)"))
{
cmd.Connection = con;
//cmd.Parameters.AddWithValue("#1", startlocationtxtbox.SelectedText);
//cmd.Parameters.AddWithValue("#2", endlocationtxtbox.SelectedText);
cmd.Parameters.AddWithValue("#3", depotidcombobox.SelectedValue);
cmd.Parameters.AddWithValue("#4", jobtypecombobox.SelectedValue);
cmd.Parameters.AddWithValue("#5",customeridcombobox.SelectedValue);
con.Open();
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
}

How to get data when combo box is selected windows Form c#

private void namecombo_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
sqlconn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM Customer WHERE Name = '" + this.namecombo.SelectedItem.ToString() + "' ", sqlconn);
sqlcmd.ExecuteNonQuery();
DataTable dtbl = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd);
adapter.Fill(dtbl);
foreach(DataRow dr in dtbl.Rows)
{
accountnumtxtbox.Text = dr["acount_name"].ToString();
phonetxtbox.Text = dr["phone_number"].ToString();
officenumtxtbox.Text = dr["office_number"].ToString();
addresstxtbox.Text = dr["Address"].ToString();
}
sqlconn.Close();
}
}
this doesn't work at all whats the problem?
You try to do it this way, just adapt it to your needs.
string sql = "SELECT * FROM Customers WHERE LastName = #lastName AND FirstName = #firstName";
UserAccount account = UserAccount.Empty;
using (SqlCommand cmd = new SqlCommand(sql, sqlConnection))
{
SqlParameter _firstName = new SqlParameter("#firstName", SqlDbType.NVarChar);
SqlParameter _lastName = new SqlParameter("#lastName", SqlDbType.NVarChar);
_firstName.Value = account.FirstName;
_lastName.Value = account.LastName;
cmd.Parameters.Add(_firstName);
cmd.Parameters.Add(_lastName);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
if (dataSet.Tables.Count > 0)
{
if (dataSet.Tables[0].Rows.Count > 0)
{
DataRow row = dataSet.Tables[0].Rows[0];
//fill your properties with the results
}
}
adapter.Dispose();
dataSet.Dispose();
}
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
sqlconn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM Customer WHERE Name = N'" + this.customergrid.SelectedRows + "' ", sqlconn);
sqlcmd.ExecuteNonQuery();
DataTable dtbl = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd);
adapter.Fill(dtbl);
foreach (DataRow dr in dtbl.Rows)
{
accountnumtxtbox.Text = dr["acount_name"].ToString();
phonetxtbox.Text = dr["phone_number"].ToString();
officenumtxtbox.Text = dr["office_number"].ToString();
addresstxtbox.Text = dr["Address"].ToString();
}
sqlconn.Close();
}

Object can't be "InvalidCastException: The OleDbParameter" in catch

I an trying to do a simple task of reading from one table "tab2" in a database->save to xml and then reload it into table "tab1" both have the same structure, I asked previously and received the following code as an answer.
I am having problems I am now getting the database filed ONCE per item but with a date time stamp I don't think its writing the XML from reading the database properly I am running it twice to get the schema and once for data.
private void button1_Click(object sender, EventArgs e)
{
try
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.accdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
//Conn.Close();//severl times connection has been open
Conn.Open();
DataSet ds = new DataSet();
ds.ReadXml(#"c:\\temp\\tab2.xml");
OleDbCommand cmd = new OleDbCommand();
//OleDbCommand cmd1 = new OleDbCommand();
DataTable dtCSV = new DataTable();
dtCSV = ds.Tables[0];
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
//cmd1.Connection = Conn;
for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
{
//for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
//{
// //cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
//}
cmd.Parameters.Clear();
if (dtCSV.Columns.Count > 1)
{
//command.Parameters.Add(new OleDbParameter("#EMPID", Convert.Tostring(empsplitIt[1])));
//cmd.Parameters.Add(dtCSV.Rows[row][0]);
cmd.Parameters.Add(new OleDbParameter("#Field1", Convert.ToString(dtCSV.Rows[row][0])));
cmd.Parameters.Add(new OleDbParameter("#dtCSV", Convert.ToString(dtCSV.Rows[row][1])));
cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (? , ?)");
cmd.ExecuteNonQuery();
}
}
//Conn.Close();
}
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
private void button2_Click(object sender, EventArgs e)
{
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
string strSql = "Select * from Table1"; //only launch in main
richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";
try
{
OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\\temp\\names.mdb; Persist Security Info = False");
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "fname,sname");
// Extract data set to XML file
ds.WriteXml(#"c:\\temp\\tab2.xml", XmlWriteMode.WriteSchema);
ds.WriteXml(#"c:\\temp\\tab2.xml");
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
}
}
}
I find from my code that there is two different connection strings with in it when I putin the corect spelling correcting these it now fails on the line
dtCSV = ds.Tables[0];
with this
Error System.IndexOutOfRangeException: Cannot find table 0.
at System.Data.DataTableCollection.get_Item(Int32 index)
at WindowsFormsApp8.Form1.button1_Click(Object sender, EventArgs e) in
Code:
private void button1_Click(object sender, EventArgs e)
{
try
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
//Conn.Close();//severl times connection has been open
Conn.Open();
DataSet ds = new DataSet();
ds.ReadXml(#"c:\\temp\\tabel2.xml");
OleDbCommand cmd = new OleDbCommand();
//OleDbCommand cmd1 = new OleDbCommand();
DataTable dtCSV = new DataTable("tabel1");
dtCSV = ds.Tables[0];
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
//cmd1.Connection = Conn;
for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
{
//for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
//{
// //cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
//}
cmd.Parameters.Clear();
if (dtCSV.Columns.Count > 1)
{
//command.Parameters.Add(new OleDbParameter("#EMPID", Convert.Tostring(empsplitIt[1])));
//cmd.Parameters.Add(dtCSV.Rows[row][0]);
cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[row][0])));
cmd.Parameters.Add(new OleDbParameter("#field2", Convert.ToString(dtCSV.Rows[row][1])));
cmd.CommandText = ("INSERT INTO tabel1 ( field1, field2) VALUES (? , ?)");
cmd.ExecuteNonQuery();
}
}
//Conn.Close();
}
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
private void button2_Click(object sender, EventArgs e)
{
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
string strSql = "Select * from tabel2"; //only launch in main
richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";
try
{
OleDbConnection con = new OleDbConnection(ConnString);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "fname,sname");
// Extract data set to XML file
ds.WriteXml(#"c:\\temp\\tabel2.xml", XmlWriteMode.WriteSchema);
ds.WriteXml(#"c:\ \temp\\tabel2.xml");
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
}
}
}

to clear the data of datagridview

I have a tabcontrol, it has 9 tabpage collection each tabpage has a datagridview and a searchbox.
private void txtsrchesd_TextChanged(object sender, EventArgs e)
{
if (txtsrchesd.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM esd_view where department like '" + txtsrchesd.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgesd.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
private void txtsrchope_TextChanged(object sender, EventArgs e)
{
if (txtsrchope.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view where department like '" + txtsrchope.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
The output of the other datagridview appears on the other datagridview , how can I clear the output of the datagridview as I clear what I type on my searchbox
hope you understand , thank you for the help
When you are checking with:
{
if (txtsrchope.Text != "")
{}
.....
}
In the else part you don't need to fire the same query as when:
txtsrchop.text ==""
You can replace your else part by this code:
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}

How to debug "There is already an open DataReader associated with this Command which must be closed first" in C#?

I have written code to filter data from database(filtering is done by two dropdownlists and between 2 dates). I am getting an error
There is already an open DataReader associated with this Command which must be closed first.
this is my front end
public partial class data : System.Web.UI.Page
{
SqlConnection con;
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnshow_Click(object sender, EventArgs e)
{
if ((ddldept.SelectedValue == "all") && (ddldesig.SelectedValue!="all") )
{
con = new SqlConnection(constring);
con.Open();
string desig = ddldesig.SelectedValue;
DateTime mydate;
mydate = Convert.ToDateTime(tbfrom.Text);
string from = Convert.ToString(mydate);
mydate = Convert.ToDateTime(tbto.Text);
string to = Convert.ToString(mydate);
SqlCommand cmddeptall = new SqlCommand("select * from registration where Department IN('Computer Science Engineering','Mechanical Engineering','Electrical And Electronics','Electronics And Communication','Civil Engineering','Science And Humanity') AND PostAppliedFor='"+desig+"' AND (RegisteredDate BETWEEN '"+from+"' AND '"+to+"')",con);
cmddeptall.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmddeptall);
DataSet ds = new DataSet();
da.Fill(ds, "registration");
GridView1.DataSource = ds.Tables["registration"];
GridView1.DataBind();
con.Close();
}
else if ((ddldept.SelectedValue == "all") && (ddldesig.SelectedValue == "all"))
{
SqlConnection con;
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
con = new SqlConnection(constring);
try
{
con.Open();
DateTime mydate;
mydate = Convert.ToDateTime(tbfrom.Text);
string from = Convert.ToString(mydate);
mydate = Convert.ToDateTime(tbto.Text);
string to = Convert.ToString(mydate);
string query = "select * from registration where Department IN('Computer Science Engineering','Mechanical Engineering','Electrical And Electronics','Electronics And Communication','Civil Engineering','Science And Humanity') AND PostAppliedFor IN('Principal','Professor','Associate Professor','Assistant Professor','Placement Officer','SoftSkills Trainer','Administrative Officer','Office Superintendent','Lab Technician') AND (RegisteredDate BETWEEN '" + from + "' AND '" + to + "')";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "registration");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
else if ((ddldept.SelectedValue != "all") && (ddldesig.SelectedValue != "all"))
{
con = new SqlConnection(constring);
con.Open();
string desig = ddldesig.SelectedValue;
string dept = ddldept.SelectedValue;
DateTime mydate;
mydate = Convert.ToDateTime(tbfrom.Text);
string from = Convert.ToString(mydate);
mydate = Convert.ToDateTime(tbto.Text);
string to = Convert.ToString(mydate);
SqlCommand cmddeptall = new SqlCommand("select * from registration where Department='"+dept+"' AND PostAppliedFor='"+desig+"' AND (RegisteredDate BETWEEN '" + from + "' AND '" + to + "')", con);
cmddeptall.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmddeptall);
DataSet ds = new DataSet();
da.Fill(ds, "registration");
GridView1.DataSource = ds.Tables["registration"];
GridView1.DataBind();
con.Close();
}
con.Close
}
Problem is that you are not disposing any objects properly. You should make database calls as mentioned below:
var ds = new DataSet();
if ((ddldept.SelectedValue == "all") && (ddldesig.SelectedValue != "all"))
{
using (var con = new SqlConnection(constring))
{
con.Open();
string desig = ddldesig.SelectedValue;
DateTime mydate;
mydate = Convert.ToDateTime(tbfrom.Text);
string from = Convert.ToString(mydate);
mydate = Convert.ToDateTime(tbto.Text);
string to = Convert.ToString(mydate);
using (var cmddeptall = new SqlCommand("select * from registration where Department IN('Computer Science Engineering','Mechanical Engineering','Electrical And Electronics','Electronics And Communication','Civil Engineering','Science And Humanity') AND PostAppliedFor='" + desig + "' AND (RegisteredDate BETWEEN '" + from + "' AND '" + to + "')", con))
{
using (var da = new SqlDataAdapter(cmddeptall))
{
da.Fill(ds, "registration");
}
}
}
}
else if ((ddldept.SelectedValue == "all") && (ddldesig.SelectedValue == "all"))
{
// Code Here
}
else if ((ddldept.SelectedValue != "all") && (ddldesig.SelectedValue != "all"))
{
// Code Here
}
Note: Moreover, I would suggest you to create separate function to call database and retrieve dataset based on query you have made. There is no need of writing same code again and again.
You don't need to execute the reader when you use the command in the SqlDataAdapter.Constructor, that's done implicitly at da.Fill. So remove the first line:
cmddeptall.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmddeptall);

Categories