简体   繁体   中英

Bind grid view data from existing code, current date

I want to using the code below and display in GridView. The situation is, when user click on GET CURRENT DATE TRANS, GridView will display the today date as the result. I already insert the GridView id as GridView1

string connetionString = null;
        SqlConnection connection;
        SqlCommand command;
        string sql = null;

        connetionString = "Data Source=AXSQL;Initial Catalog=UniKL;User ID=aten;Password=pass@WORD1";
        sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";

        GridView1.DataBind();

        connection = new SqlConnection(connetionString);

        connection.Open();
        command = new SqlCommand(sql, connection);
        command.ExecuteNonQuery();
        command.Dispose();
        connection.Close();  

I guess your column SubmittedDateTime is of type DateTime in sql so you also need to cast this column in date to match the current date like this

cast([SubmmitedDateTime] as Date) = cast(getdate() as date);

So you query will look like this

sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE cast([SubmmitedDateTime] as Date) = cast(getdate() as date)";

One suggestion would be to change:

sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";

to something like:

sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = " + DateTime.Now.toShortDateString();

or

sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = " + DateTime.Now.toString("yyyy-MM-dd");

You are not assigning data source to GridView1. Please use the following code:

string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;

connetionString = "Data Source=AXSQL;Initial Catalog=UniKL;User ID=aten;Password=pass@WORD1";
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";

//GridView1.DataBind();

connection = new SqlConnection(connetionString);
connection.Open();
command = new SqlCommand(sql, connection);

//Get data into a reader
SqlDataReader sr = command.ExecuteReader();
//command.ExecuteNonQuery();

//Set the datasource of GridView1
GridView1.DataSource = sr;
GridView1.DataBind();


command.Dispose();
connection.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM