Results 1 to 3 of 3

Thread: using the sqldatasource UpdateCommand

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Aug 2005
    Posts
    150

    using the sqldatasource UpdateCommand

    If I have a gridview with a default mode set as (Edit).

    I don't want to use the Edit,Update,Cancel buttons in the gridview , I simply want to add a button somewhere in the page , and once that button is clicked the gridview contents should be updated as if I clicked on the (update) button which belongs to the gridview.

    I thought I can call the UpdateCommand !! because I simply want to execute this command and that's it.

  2. #2
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: using the sqldatasource UpdateCommand

    You have to loop through all the rows of the gridview, get each value out and construct your SQL statement yourself, then execute it. You can't use UpdateCommand for your particular scenario because you are attempting to update all the rows together.

  3. #3
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: using the sqldatasource UpdateCommand

    Look, I even found an example

    Code:
    private void Update()
    
    {
    
    StringBuilder sb = new StringBuilder();
    
    // build the query
    
    foreach (GridViewRow row in GridView1.Rows)
    
    {
    
    sb.Append("UPDATE Users SET FirstName = '");
    
    sb.Append((row.FindControl("txtFirstName") as TextBox).Text);
    
    sb.Append("',");
    
    sb.Append("LastName = '");
    
    sb.Append((row.FindControl("txtLastName") as TextBox).Text);
    
    sb.Append("', ");
    
    sb.Append("ClassCode = '");
    
    sb.Append((row.FindControl("txtClassCode") as TextBox).Text);
    
    sb.Append("'");
    
    sb.Append(" WHERE UserID = ");
    
    sb.Append(Convert.ToInt32((row.FindControl("lblUserID") as Label).Text));
    
    sb.Append(" ");
    
    }
    
    string connectionString = "Server=HCUBE008;Database=School;Trusted_Connection=true";
    
    SqlConnection myConnection = new SqlConnection(connectionString);
    
    SqlCommand myCommand = new SqlCommand(sb.ToString(), myConnection);
    
    myConnection.Open();
    
    myCommand.ExecuteNonQuery();
    
    myConnection.Close();
    
    }
    And don't complain if you wanted it in VB.NET, the languages are almost identical.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width