开发者

Insert Datetimepicker text in SQL Database

how to Insert Datetimepicker text in SQL Database as datetime data开发者_开发知识库type


In order to parse the datetime from datetime picker you can do the following:

string dt = dateTimePicker.Value.ToString("yyyy-MM-dd hh:mm:ss");

And then in order to insert it in your database you can do:

Insert into table (id, mytime) 
values("5",  CONVERT(datetime, CONVERT( varchar(11), dt, 101))

If you need information on how to access your database you can read the following article in CodeProject


Parse the text in C#, and insert the parsed DateTime. Example:

var date = new DateTime(dateTimePickerText);
InsertIntoSqlDatabase(date); // Code for inserting here.


You can insert date as DateTime directly (without converting into string) by using DataRow. For example:

  using (SqlConnection sqlconn = new SqlConnection())
        {
            sqlconn.ConnectionString = @"Data Source = #your_serwer\instance#; Initial Catalog = #db_name#; User Id = #user#; Password = #pwd#;";
            sqlconn.Open();

            // select your date and a key index field on a table (e.g. "id")
            string sql = "select id, some_date from table_1 where id = 1 ";

            using (SqlDataAdapter adapter = new SqlDataAdapter(sql, sqlconn))
            {
                using (DataTable table = new DataTable())
                {
                    adapter.Fill(table);                       

                    DataRow r = null;
                    if (table.Rows.Count == 1)
                        r = table.Rows[0];   // case, when there is an row for update
                    else
                        r = table.NewRow();  // case, when there is no row, and you would like to insert one

                    r.BeginEdit();
                    // here you assign your value
                    r["some_date"] = dateTimePicker.Value;
                    r.EndEdit();

                    if (table.Rows.Count == 0)
                    {
                        // in case of insert, provide here some other values for other non null columns like
                        r["id"] = 2;
                        // also you have to add this row into DataTable
                        table.Rows.Add(r);
                    }

                    // this will update the database
                    SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(adapter);
                    adapter.Update(table);
                }
            }
        }

Hope, this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜