-1
<asp:TextBox ID="txtstartdate" class="form-control" autocomplete="off" CssClass="datepicker1" runat="server"></asp:TextBox>

<asp:TextBox ID="txtenddate" class="form-control" autocomplete="off" CssClass="datepicker2" runat="server"></asp:TextBox>

<asp:TextBox id="txtreason" TextMode="multiline"  runat="server" />

<asp:Button ID="submit" CssClass="login" runat="server" Text="Submit" OnClick="Submit_click" />

Using the Submit_click I want to insert data into table between the 2 dates selected on txtstartdate and txtenddate. txtreason should repeat for all the dates on the table.

For example if select dates 07/30/2018 and 08/04/2018 on txtstartdate and txtenddate and enter "hello" as reason for txtreason, I should get all the dates between 07/30/2018 and 08/04/2018 in the ldate column on the data table and hello should be repeated on reason column for 6 times for each individual dates. The below method works like a charm if you change date format.

protected void Submit_click(object sender, EventArgs e)
{
        DateTime startdate = Convert.ToDateTime(txtstartdate.Text);
        DateTime enddate = Convert.ToDateTime(txtenddate.Text);
        for (DateTime date = startdate; date <= enddate; date = date.AddDays(1))
        {
            try
            {
                string MyConString = "SERVER=localhost;DATABASE=mydb;UID=myid;PASSWORD=abc123;";
                MySqlConnection connection = new MySqlConnection(MyConString);
                string cmdText = "INSERT INTO approved(agentlogin ,leavetype ,date ,time, reason)VALUES ( @login, @type, @date, 'Full day', @reason)";
                MySqlCommand cmd = new MySqlCommand(cmdText, connection);
                cmd.Parameters.AddWithValue("@login", Label1.Text);
                cmd.Parameters.AddWithValue("@type", ddlleavetype.Text);
                cmd.Parameters.AddWithValue("@date", date);
                cmd.Parameters.AddWithValue("@reason", txtreason.Text);

                connection.Open();

                int result = cmd.ExecuteNonQuery();
                connection.Close();

                //lblError.Text = "Data Saved";

            }
            catch (Exception)
            {
                Console.Write("not entered");
                //lblError.Text = ex.Message;
            }
        }
    }
  • Where is your MySQL code? – marekful Jul 30 '18 at 08:12
  • 1
    *Is it possible to do that?* - yes, probably, but i see so many dangerous and arguably bad things happening here, that i don't know where i'd start cleaning it up. – Timothy Groote Jul 30 '18 at 08:12
  • lol. What a good question with `"Insert query"` – Antoine V Jul 30 '18 at 08:13
  • Its hard to help without knowing the database schema, `insert query` is a too poor description of the tables involved. – Cleptus Jul 30 '18 at 08:14
  • 1
    @bradbury9 to solve OP's mentioned problem, you don't need to know what the table looks like. – Timothy Groote Jul 30 '18 at 08:15
  • There doesnt seem to be a mySQL connection in this.. Other than you dont actually run your command to add the data, what specifically are you struggling with – BugFinder Jul 30 '18 at 08:17
  • @TimothyGroote I read it twice and I dont get what the hell is trying to accomplish. "insert data beetween two dates" is imho not enought description of a problem xD – Cleptus Jul 30 '18 at 08:17
  • @bradbury9 he could've been clearer, yes. but i think he wants to insert records per day between the entered dates ;) – Timothy Groote Jul 30 '18 at 08:18
  • 1
    @TimothyGroote OK, then like tsql's recursive CTE + insert. – Cleptus Jul 30 '18 at 08:19
  • 1
    you can do insert multiple records with only one `insert` command, the syntax is `insert into tableName (select that returns multiple rows)`. The trick here is doing it using a recursive CTE in the `select` part, check the [mysql CTE doc](https://dev.mysql.com/doc/refman/8.0/en/with.html) to get the records between two given dates, one for each day. BTW, posting this as a comment instead an answer because is not an actual query, only some guidance. – Cleptus Jul 30 '18 at 08:25
  • Related, not duplicated, but is a good sample on a recursive CTE between two dates. https://stackoverflow.com/questions/27489564/for-each-day-between-two-dates-add-a-row-with-the-same-info-but-only-that-day-i – Cleptus Jul 30 '18 at 08:34
  • Thanks to your edit I noticed this is not mySQL, but MS access. – Cleptus Jul 30 '18 at 09:52
  • @bradbury9 yes but if you could suggest it on mySQL, I will integrate it with my code. I'm trying with both mySQL and OleDb –  Jul 30 '18 at 10:10
  • I proposed an answer that would work on mySQL but not on access, answer that I have deleted because is no longer valid if you are using access. You should notice that there are some thing that work in proper databases (mysql, sql server, oracle) but do not work in ejem... access. – Cleptus Jul 30 '18 at 10:14
  • @bradbury9 Alright I'll try it on mySQL and post the edit –  Jul 30 '18 at 10:26
  • @bradbury9 tried with MySql, still not working –  Jul 30 '18 at 11:46

2 Answers2

1

This is why you should use models, and utilise the proper types rather than keep everything a string.

While not perfect, a step in the right direction would be something like this : (Keep in mind that i haven't solved every single problem. there is plenty of room for improvement)

public class DateRangeModel
{
    public DateTime From {get; set;}
    public DateTime To   {get; set;}

    public IEnumerable<DateTime> DaysInRange {
        get{
            for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
            {
                yield date;
            }
        }
    }

    public DateRangeModel(string from, string to)
    {
        From = GetDate(from);
        To = GetDate(to);
    }

    private static DateTime GetDate(string string_date)
    {
        DateTime dateValue;
        if (DateTime.TryParse(string_date, out dateValue))
            return dateValue;
        else
            throw new Exception("Unable to convert '{0}' to a date.", string_date);

    }
}

protected void Submit_click(object sender, EventArgs e)
{

    DateRangeModel dateRange = new DateRangeModel(txtstartdate.Text, txtenddate.Text);

    OleDbConnection scn = new OleDbConnection();
    scn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data   Source=/mysource;";

    foreach(var dt in dateRange.DaysInRange)
    {
        OleDbCommand scmd = new OleDbCommand("Insert query", scn);
        scmd.CommandType = CommandType.Text;
        scmd.Parameters.Clear();
        scmd.Parameters.AddWithValue("@date1", dt);
        scmd.Parameters.AddWithValue("reason", txtreason);
        //etc (finish your insert stmt here).
    }  
}
Timothy Groote
  • 8,614
  • 26
  • 52
  • Thanks, but how can I get the values into insert query? –  Jul 30 '18 at 08:48
  • 1
    @PrakashKumar that is a different problem, you are asking now how do you make an insert into a table. You should notice we know nothing abut the acual table and column names. – Cleptus Jul 30 '18 at 08:50
  • @bradbury9: When you change code make sure to test it beforehand. Your edit writes twice to To but never to From. – BDL Jul 30 '18 at 09:08
  • @BDL thanks for the warning, feel free to reject the edit or correct the variable assignment. – Cleptus Jul 30 '18 at 09:42
0

Use the below method to change the date format. Hope this helps

protected void Submit_click(object sender, EventArgs e)
{
    DateTime startdate = Convert.ToDateTime(txtstartdate.Text);
    DateTime enddate = Convert.ToDateTime(txtenddate.Text);
    for (DateTime date = startdate; date <= enddate; date = date.AddDays(1))
    {
        try
        {
            var shtdate = date.ToShortDateString();
            string MyConString = "SERVER=localhost;DATABASE=mydb;UID=myid;PASSWORD=abc123;";
            MySqlConnection connection = new MySqlConnection(MyConString);
            string cmdText = "INSERT INTO approved(agentlogin ,leavetype ,date ,time, reason)VALUES ( @login, @type, @date, 'Full day', @reason)";
            MySqlCommand cmd = new MySqlCommand(cmdText, connection);
            cmd.Parameters.AddWithValue("@login", Label1.Text);
            cmd.Parameters.AddWithValue("@type", ddlleavetype.Text);
            cmd.Parameters.AddWithValue("@date", shtdate);
            cmd.Parameters.AddWithValue("@reason", txtreason.Text);

            connection.Open();

            int result = cmd.ExecuteNonQuery();
            connection.Close();

            //lblError.Text = "Data Saved";

        }
        catch (Exception)
        {
            Console.Write("not entered");
            //lblError.Text = ex.Message;
        }
    }
}
prkash
  • 427
  • 1
  • 5
  • 23