简体   繁体   中英

C# - Problem with DataGridView and DateTimePicker

I need help in understanding where I'm wrong, I'm using a DataGridView to allow the display of a table in the Form and I wanted to insert the function of selecting a range of dates with two DateTimePicker fields and start the SELECT Statement with a "CERCA" button, when, however, I start the program and try to make the selection in the DataGridView field only an empty line appears even if I have set two SelectCommand instructions. I don't understand where I'm wrong.

    public DataGridView_Maria()
    {
        InitializeComponent();
    }
    SqlConnection conn = new SqlConnection("Data Source=192.168.0.51;Initial 
    Catalog=Archivio_Stipendi;User ID=sa;Password=NI2000ma;");

    private void CERCA_Button_Click(object sender, EventArgs e)
    {
        conn.Open();
        'SqlDataAdapter sdf = new SqlDataAdapter(@"SELECT GIORNO, RIPOSO, ORE_LAVORO, COMPENSO_LAVORO FROM [dbo].[MARIA_VARAVALLO] WHERE GIORNO BETWEEN '@DA_GIORNO' AND '@A_GIORNO';", conn);'

        sdf.SelectCommand.Parameters.AddWithValue("@DA_GIORNO", Da_Mar_DTP.Text);
        sdf.SelectCommand.Parameters.AddWithValue("@A_GIORNO", A_Mar_DTP.Text);

        DataTable sd = new DataTable();
        sdf.Fill(sd);
        DataGridView_Mar.DataSource = sd;

        conn.Close();
    }
}

I just made the change as per your advice and, by setting the date range directly from the query, the DataGridView works, hitting the "CERCA" button displays the set date. Fantastic! But I still don't know why the DataTimePicker gives him problems ...

This is the modified code:

    public DataGridView_Maria()
    {
        InitializeComponent();
    }
    SqlConnection conn = new SqlConnection("Data Source=192.168.0.51;Initial Catalog=Archivio_Stipendi;User ID=sa;Password=NI2000ma;");
    private void CERCA_Button_Click(object sender, EventArgs e)
    {
        conn.Open();
        SqlDataAdapter sdf = new SqlDataAdapter(@"SELECT GIORNO, RIPOSO, ORE_LAVORO, COMPENSO_LAVORO FROM [dbo].[MARIA_VARAVALLO] WHERE GIORNO BETWEEN 'Lunedì 09 Marzo 2020' AND 'Lunedì 09 Marzo 2020';", conn);
        DataTable sd = new DataTable();
        sdf.Fill(sd);
        DataGridView_Mar.DataSource = sd;

        conn.Close();
    }
}

}

Instead of the Text properties of the DateTimePicker (s), try the Value properties, like this:

sdf.SelectCommand.Parameters.AddWithValue("@DA_GIORNO", Da_Mar_DTP.Value);
sdf.SelectCommand.Parameters.AddWithValue("@A_GIORNO", A_Mar_DTP.Value);

Edit … I think you'll also need to remove the ' (single quotes) around the parameters in the query:

WHERE GIORNO BETWEEN '@DA_GIORNO' AND '@A_GIORNO'

… becomes:

WHERE GIORNO BETWEEN @DA_GIORNO AND @A_GIORNO

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