Getting data from database by getting date from DateTimePicker - c#

I am trying to get data in gridview on the basis of the date that is entered in dateTimePicker. But, I am getting null reference runtime error on if condition where I have used equals function to compare two strings.
ReportFrom.cs
private void button1_Click(object sender, EventArgs e)
{
string date = dateTimePicker.Value.ToShortDateString();
reportLayer.MakeDailyReport(date, dataGridViewReport);
}
ReportLayer.cs
private SqlConnection con = new SqlConnection("Data Source=CHAMP-PC;Initial Catalog=ProcessSale;Integrated Security=True");
private SqlCommand cmd;
private SqlDataAdapter adapt;
public void MakeDailyReport(string givenDate, DataGridView view)
{
try
{
con.Open();
DataTable dt = new DataTable();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = #datePicker", con);
cmd.Parameters.AddWithValue("#datePicker", givenDate);
cmd.ExecuteNonQuery();
object dateObject = cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject);
string givenDateString = Convert.ToString(givenDate);
// string DBdate = dateObject.ToString();
if (dateObject.Equals(givenDate))
{
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
catch (Exception a)
{
MessageBox.Show(a.Message);
con.Close();
}
}

Have a look here:
Handling ExecuteScalar() when no results are returned
Additionally: Be careful with the call to Equals(). Currently you are comparing
two strings. One with a ShortDate value One with the default ToString().
Event if the dates are equal, this might return false.
A better solution would be handling both values as DateTime and use the == operator.
Thomas

Related

changing value of cell on condition in gridview - c#

I have fetched the data from SQL server to datagridview but I don't know how to change the cell value. I have to change the fetched value 1 and 0 to available and unavailable. here is my code for fetching data ... please help.
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
SqlCommand cmd = new SqlCommand("Select id as 'Book ID',name as 'Name' , status as 'Status' from book where Name = #name", con);
cmd.Parameters.AddWithValue("#name", txtFirstName.Text);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
dataGridView1.DataSource = bsource;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
Please find below answer
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
string sSql=#"Select id as 'Book ID',name as 'Name' ,
Case when status=0 then 'unavailable' else 'available '
End as 'Status' from
book where Name ='"+txtFirstName.Text +"'"
SqlCommand cmd = new SqlCommand(sSql, con);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
First of all, try to store your queries in variables. This will help you in the long run. Also, it is good practise to check whether you are connected or not before trying to send a query away to the server. It is important to remeber that when you fetch data from your server, it will most likely be seen as a string, so if you want to compare it as a number, you need to convert it first.
What you could do is something similar to what i've written below. You count the amount of answers your query returns, then loop through them and check whether they are 0 or 1. Then just replace the value with Avaliable or Unavaliable.
if (dbCon.IsConnect()){
MySqlCommand idCmd = new MySqlCommand("Select * from " + da.DataGridView1.Text, dbCon.Connection);
using (MySqlDataReader reader = idCmd.ExecuteReader()){
// List<string> stringArray = new List<string>(); // you could use this string array to compare them, if you like this approach more.
while (reader.Read()){
var checkStatus= reader["Status"].ToString();
Console.WriteLine("Status: " + checkStatus.Split(' ').Count()); //checks how many items you've got.
foreach (var item in checkStatus.Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray()){
var item2 = 0.0; // your 0 or 1 for avaliable or unavaliable..
try{
item2 = double.Parse(item.ToString());
if(strcmp(item2,'0') == 1){ //assuming you only have 0's and 1's.
item2 = "unavaliable";
}else{
item2 = "avaliable";
}
}
catch (Exception){
//do what you want
}
Console.WriteLine("item: " + item2);
}
}
dbCon.Close();
}
}
return //what you want;
}

No data is showing in combobox

I am trying show some data from a database to a combobox based on another combobox selection with this code:
private void metroComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dt = new DataSet();
try
{
DateTime startDate = Convert.ToDateTime(metroLabel8.Text);
DateTime endDate = Convert.ToDateTime(metroLabel9.Text);
// Make sql readable
string sql =
#"Select [LedId],[LedName] from [Ledger] where Date >= #prmStartDate and Date <= #prmEndDate";
// wrap IDisposable (SqlCommand) into using
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#prmStartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#prmEndDate", SqlDbType.DateTime).Value = endDate;
con.Close();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
VoucherLedgerName_combo.DisplayMember = "LedName";
VoucherLedgerName_combo.ValueMember = "LedId";
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"];
}
}
catch(Exception exe)
{
MessageBox.Show(exe.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
But i am getting nothing in the second combobox, and I am sure that there is data in the database table Ledger. Can any one please help me to find the issue?
change your SQL statement as below(Date is reserved keyword)
string sql =
#"Select [LedId],[LedName] from [Ledger] where [Date] >= #prmStartDate and [Date] <= #prmEndDate";
You need to give table name when you fill dataset since you are using the name when you set data source
da.Fill(dt, "Ledger");
or set the data source as below
VoucherLedgerName_combo.DataSource = dt.Tables[0];
DataRow dr = dt.NewRow();
dr["Ledger"] = "--Select All--";
dt.Rows.InsertAt(dr, 0);
You can change from
da.Fill(dt);
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"];
to
da.Fill(dt, "Ledger");
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"].DefaultView;
else
VoucherLedgerName_combo.DataSource = dt.Tables[0].DefaultView;
or
VoucherLedgerName_combo.DataSource = dt;

Invalid column name on adapter fill

I am getting a System.Data.SqlClient.SqlException with additional information of an Invalid column name Jun on Fill function while I am entering 19-jun-2016 from the datetimePicker and here is a Jun is a month but it taking it as a column.
ReportForm.cs
public void MakeDailyReport(string givenDate, DataGridView view)
{
con.Open();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = #datePicker", con);
cmd.Parameters.AddWithValue("#datePicker", givenDate);
cmd.ExecuteNonQuery();
DateTime dateObject = (DateTime)cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject.ToShortDateString());
string givenDateString = Convert.ToString(givenDate);
if (dateObjectstring == givenDateString)
{
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
Don't use string concatenation to build your query but sql parameters with the correct type. That will also prevent you from sql injection and other possible issues (like this one).
adapt = new SqlDataAdapter("SELECT [Date] FROM FinalSales where [Date] = #givenDate", con);
var dateParameter = adapt.SelectCommand.Parameters.Add("#givenDate", SqlDbType.DateTime);
dateParameter.Value = dateTimePicker.Value.Date; // not string but the correct type DateTime
Note that i've also used dateTimePicker.Value.Date to ignore the time portion.

Not getting any row data from database using c# asp.net.

I can not get any row data from database using c# asp.net.I am trying to fetch one row data from my DB but it is not returning any row.I am using 3-tire architecture for this and i am explaining my code below.
index.aspx.cs:
protected void userLogin_Click(object sender, EventArgs e)
{
if (loginemail.Text.Trim().Length > 0 && loginpass.Text.Trim().Length >= 6)
{
objUserBO.email_id = loginemail.Text.Trim();
objUserBO.password = loginpass.Text.Trim();
DataTable dt= objUserBL.getUserDetails(objUserBO);
Response.Write(dt.Rows.Count);
}
}
userBL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
userDL objUserDL = new userDL();
try
{
DataTable dt = objUserDL.getUserDetails(objUserBO);
return dt;
}
catch (Exception e)
{
throw e;
}
}
userDL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
SqlConnection con = new SqlConnection(CmVar.convar);
try
{
con.Open();
DataTable dt = new DataTable();
string sql = "SELECT * from T_User_Master WHERE User_Email_ID= ' " + objUserBO.email_id + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(dt);
con.Close();
return dt;
}
catch(Exception e)
{
throw e;
}
}
When i am checking the output of Response.Write(dt.Rows.Count);,it is showing 0.So please help me to resolve this issue.
It looks like your your query string has a redundant space between ' and " mark. That might be causing all the trouble as your email gets space in front.
It is by all means better to add parameters to your query with use of SqlConnection.Parameters property.
string sql = "SELECT * from T_User_Master WHERE User_Email_ID=#userID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#userID", SqlDbType.NVarChar);
cmd.Parameters["#userID"].Value = objUserBO.email_id;

Populating TextBox, The data type is not valid for the boolean operation

I got a ComboBox with a table as data source, ID as a value member and a name as a display member.
Selecting a name from the ComboBox should populate 6 TextBoxes with data.
Exception:
The data type is not valid for the boolean operation. [ Data type (if known) = int,Data type (if known) = nvarchar ]
Code:
void FillComboBox()
{
//Fill Combo Box
SqlCeDataAdapter da = new SqlCeDataAdapter(" SELECT CustomerID, Name FROM Customers", clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
cBox1.DataSource = ds.Tables[0];
cBox1.ValueMember = "CustomerID";
cBox1.DisplayMember = "Name";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
clsMain.con.ConnectionString = #"Data Source=|DataDirectory|\Database\Sales.sdf";
clsMain.con.Open();
FillComboBox();
}
private void btnSave_Click(object sender, EventArgs e)
{
//Save Button
SqlCeCommand cmd = new SqlCeCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " INSERT INTO Customers (Name, Phone1, Phone2, Address, Notes) VALUES (#Name, #Phone1, #Phone2, #Address, #Notes) ";
cmd.Connection = clsMain.con;
cmd.Parameters.AddWithValue("#Name", txt2.Text.Trim());
if (txt3.Text != "")
{
cmd.Parameters.AddWithValue("#Phone1", Convert.ToInt32(txt3.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone1", Convert.DBNull);
}
if (txt4.Text != "")
{
cmd.Parameters.AddWithValue("#Phone2", Convert.ToInt32(txt4.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone2", Convert.DBNull);
}
cmd.Parameters.AddWithValue("#Address", txt5.Text.Trim());
cmd.Parameters.AddWithValue("#Notes", txt6.Text.Trim());
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
private void cBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (cBox1.SelectedIndex >= 0)
{
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue.ToString();
SqlCeDataAdapter da = new SqlCeDataAdapter(Code, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
txt1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
txt2.Text = ds.Tables[0].Rows[0]["Name"].ToString();
txt3.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
txt4.Text = ds.Tables[0].Rows[0]["Phone2"].ToString();
txt5.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txt6.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
}
}
Table Details:
To follow up on my comment (with the caveat that I have never worked with SQL CE, but I'm pretty sure (99.9%) that this is correct).
In you SQL query string, you surround the customer id with single quotes ('). You use single quotes in SQL ("nomral" SQL at least) for character (char\varchar etc) and date values. You pass numeric values without single quotes.
You didn't indicate what line was giving you the exception, but based on the table structure and what you are doing (you gave good detail in your question, by the way), it seems that the error message is telling you that you're trying to compare an int to a varchar, and that's not allowed (because they are different data types, as the error indicates).
To resolve this, simply remove the single quotes from the value in your WHERE clause and construct your query as follows:
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue;
Thank you, Its working for me.
I am having some customers name in comboBox2. Based on the selected name textbox will return CustomerID and Date of Allocation values.
Following are the code for that:
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if(comboBox2.SelectedIndex>0)
{
con = new SqlCeConnection(s);
con.Open();
string code = "select CustomerID,Date_of_Allocation from lockerdetails
where CustomerName='" + comboBox2.SelectedValue.ToString() + "'";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, con);
SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
textBox1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
textBox5.Text = ds.Tables[0].Rows[0]["Date_of_Allocation"].ToString();
}
}
catch(SystemException se)
{
MessageBox.Show(se.Message);
}

Categories