c# – Specified cast is not valid?

c# – Specified cast is not valid?

From your comment:

this line DateTime Date = reader.GetDateTime(0); was throwing the exception

The first column is not a valid DateTime. Most likely, you have multiple columns in your table, and youre retrieving them all by running this query:

SELECT * from INFO

Replace it with a query that retrieves only the two columns youre interested in:

SELECT YOUR_DATE_COLUMN, YOUR_TIME_COLUMN from INFO

Then try reading the values again:

var Date = reader.GetDateTime(0);
var Time = reader.GetTimeSpan(1);  // equivalent to time(7) from your database

Or:

var Date = Convert.ToDateTime(reader[YOUR_DATE_COLUMN]);
var Time = (TimeSpan)reader[YOUR_TIME_COLUMN];

htmlStr is string then You need to Date and Time variables to string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += <tr><td> + Date.ToString() + </td><td>  + 
                    Time.ToString() + </td></tr>;                  
                }

c# – Specified cast is not valid?

Try this:

public void LoadData()
        {
            SqlConnection con = new SqlConnection(Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False);
            SqlDataAdapter sda = new SqlDataAdapter(Select * From [Stocks].[dbo].[product], con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item[ProductCode].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item[Productname].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item[qty].ToString();                
            if ((bool)item[productstatus])
            {
                DataGridView1.Rows[n].Cells[3].Value = Active;
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = Deactive;
            }

Leave a Reply

Your email address will not be published. Required fields are marked *