Search code examples
c#sqlparametersado.netdapper

how do i supply textbox values to my sql statement using Dapper?


The error message for both button clicks is:

Additional information: The member Id of type System.Windows.Controls.TextBox cannot be used as a parameter value

    private void Button_Click(object sender, RoutedEventArgs e)

    {

        var connection = new SqlConnection(sqlConnectionString);

        Student student = new Student();

        connection.Open();
        
        var affectedRows = connection.Execute("Delete from Student Where Id = @Id", new { Id = txtStudentID });

            connection.Close();

            //return affectedRows;
    }











    private void Button_Click_1(object sender, RoutedEventArgs e)

    {
        var connection = new SqlConnection(sqlConnectionString);

        Student student = new Student();

        var affectedRows = connection.Execute("Update Student set Name = @Name, Marks = @Marks Where Id = @Id", new { Id = txtStudentID, Name = txtName.Text, Marks = txtMarks.Text });

        connection.Close();

    }  

Solution

  • You need to send the Text inside the textbox as the parameter value, not the TextBox itself

    connection.Execute(
      "Delete from Student Where Id = @Id", 
      new { Id = txtStudentID.Text }
    //                       ^^^^^
    );
    

    It would be best not to ask SQL Server to do a data conversion. If the ID column in the database is an integer, parse the string to integer on C# side:

    connection.Execute(
      "Delete from Student Where Id = @Id", 
       new { Id = int.Parse(txtStudentID.Text) }
    );
    

    Or use a NumbericUpDown control then you don't have to worry about parsing failures (only numbers can be entered)

    connection.Execute(
      "Delete from Student Where Id = @Id", 
      new { Id = (int)nudStudentID.Value }
    );
    

    Similarly if the ID is e.g. a Guid, parse it..

    Same advice for the update query - you've got the .Text on the name and the Marks (it's numeric? see parsing advice above), but not on the ID; perhaps a copypasta error


    Other bits of advice:

    You should write using var to create your connection. You don't need to make a new Student. Dapper will open/close a connection that is closed. It will leave open a connection that is opened by you. You don't use affected rows, so you don't need to capture it:

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        using var connection = new SqlConnection(sqlConnectionString);
    
        connection.Execute(
            "Update Student set Name = @Name, Marks = @Marks Where Id = @Id", 
            new { 
              Id = int.Parse(txtStudentID.Text), 
              Name = txtName.Text, 
              Marks = double.Parse(txtMarks.Text)
            }
        );
    
    }