Click here to Skip to main content
15,891,912 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello..... I've created a database in which i have saved some data along with date. Now i want to extract data from database of a particular month by selecting Calender and to display data in gridview in asp.net. Please solve my problem. My code is as of follows:
private SqlConnection cn = new SqlConnection("User Id=sa;Password=12345;Database=Satyam;Server=CHIKLU-PC");
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        cn.Open();
        try
        {
            SqlCommand cm = new SqlCommand("SELECT * FROM empreport WHERE ename='" + TextBox1.Text + "' and indate='" +Calender1.SelectedDate.Month.ToShortDateString()+ "'", cn);
            SqlDataAdapter da = new SqlDataAdapter(cm);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
        }
        cn.Close();
Posted
Updated 6-Feb-13 5:47am
v2
Comments
Richard C Bishop 6-Feb-13 11:48am    
Are you receiving any exceptions? Where does the code stop when you are debugging?
Chiklu.Soumya 6-Feb-13 11:55am    
It doesn't showing any exception. It's working only when a specific date is selected.(Calender1.SelectedDate.ToShortDateString)i'm using this code. But I want it in month and don't know how to do it.
Richard C Bishop 6-Feb-13 12:08pm    
I would just use "Calendar1.SelectedDate.Month.ToString()". Try that and see what happens.
Chiklu.Soumya 6-Feb-13 12:26pm    
No. Error. But gridview doesn't showing any data.
Richard C Bishop 6-Feb-13 12:42pm    
If you are not getting any error, than your query is not returning anything. What datatype is the field "indate" in your query?

1 solution

You need to write query to get data for a given month. Try something like following:
SQL
SELECT 
   * 
FROM
   empreport
WHERE
   MONTH(myDateColumn) = @SelectedMonthParam

Refer: MSDN: MONTH (Transact-SQL)[^]
NOTE 1: Make sure datatypes match. It returns integer , so pass integer from frontend.
NOTE 2: MONTH returns the same value as DATEPART (month, date).

BTW, the way you have implemented ADO.NET is open for SQL Injection. Read about protecting from SQL Injection here: SQL Injection Mitigation: Using Parameterized Queries[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900