I've been having some trouble finding the correct syntax to get the value of the datetime
from my SQL Server and be displayed on a datetimepicker in C#. I'm using Visual Studio 2008 and SQL Server 2005.
Below is my code, it uses datagridview with a double click event:
private void dg_DoubleClick(object sender, EventArgs e)
{
button2.Visible = true;
button5.Visible = true;
try
{
DataTable dt = new DataTable();
SqlDataAdapter dad = new SqlDataAdapter("SELECT * FROM tblSchools WHERE Number ="+
Convert.ToInt16(dg.SelectedRows[0].Cells[0].Value.ToString()) + "", conn);
dad.Fill(dt);
textBox1.Text = dt.Rows[0][1].ToString();
comboBox1.Text = dt.Rows[0][2].ToString();
textBox2.Text = dt.Rows[0][3].ToString();
textBox4.Text = dt.Rows[0][4].ToString();
textBox5.Text = dt.Rows[0][5].ToString();
textBox6.Text = dt.Rows[0][6].ToString();
dateTimePicker1.Value.Date = dt.Rows[0][7];
textBox8.Text = dt.Rows[0][8].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The error comes from this line:
dateTimePicker1.Text = dt.Rows[0][7];
it says
Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
Someone teach me the proper syntax. Thank you :)
I think that if you went
dateTimePicker1.Value = (datetime)dt.Rows[0][7];
should work
Hope this helps,
Do like this,
dateTimePicker1.Text = dt.Rows[0][7].ToString();
or
dateTimePicker1.Value = Convert.ToDateTime(dt.Rows[0][7]);
dateTimePicker1.CustomFormat = "dd-MMM-yyyy";
dateTimePicker1.Format =DateTimePickerFormat.Custom;
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.