This is my table in db
create table gridview(id bigint identity(1,1),name varchar(65),startdate varchar(1000),enddate varchar(1000),gender char(25),mobileno bigint,designition varchar(100),
country nvarchar(65),state nvarchar(65),city nvarchar(65))
i want to write a procedure for from date to to to date
once i click on button it should display only records between the two dates only pls help me
This is my procedure
create PROCEDURE sp_SearchCustomerDetailsByDate
@StartDate varchar(100),
@EndDate varchar(100)
AS
BEGIN
select * from gridview where startdate between @StartDate and @EndDate
END
This is My code for getting date
private DataTable GetDate(string fromdate, string enddate)
{
using (SqlCommand cmd = new SqlCommand("sp_SearchCustomerDetailsByDate", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@StartDate",fromdate);
cmd.Parameters.AddWithValue("@EndDate",enddate);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
This is my button1click code
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = GetDate(TextBox12.Text,TextBox13.Text);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
pls help me out
Tuhin PaulPosted Feb 24, 2023, 1:06 PM
Hi Jaya,
Your code looks mostly correct. However, there are a few minor things you could improve.
Firstly, instead of using varchar(1000) for startdate and enddate, you should use date or datetime data types. This will allow you to use the BETWEEN operator directly on the date values without having to worry about string formatting issues.
Here's the updated CREATE TABLE statement with the date columns changed to datetime data type:
Next, it's a good practice to explicitly specify the columns you want to select from the table instead of using SELECT *. This can improve query performance and reduce network traffic.
Here's the updated stored procedure code:
Finally, when passing the date values to the stored procedure, you should convert them to DateTime objects instead of passing them as strings. You can use DateTime.Parse or DateTime.TryParse to do this.
Here's the updated GetDate method:
With these changes, your code should work as expected.
Jaya PrakashPosted Feb 24, 2023, 9:12 AM
getting error sir Conversion failed when converting date and/or time from character string.
Naimish MakwanaPosted Feb 24, 2023, 8:59 AM
Hello Jaya,
Your SP whould be like below:
Thanks
Naimish Makwana