0

I have a gridview which populated via selected item on my drop down list, I don't have any problem with that. My problem is I am trying to save multiple rows on my gridview into my database, for example I have added 3 items on my gridview which looks like this:

Id  | Name
111 | Jack
222 | Nicole
333 | John

Now, I want all that under column Id which is 111, 222 and 333 will be save on my database once I click Save button I am trying the code below but it gives me an error saying "system.data.sqlclient.sqlparameter does not contain a definition for 'Values' and no extension method 'Values' accepting a first argument of type..." :

SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
    SqlCommand cmdd = new SqlCommand("Insert into profile (Id, profile_id)VALUES(@id, @profile_id", con);

    foreach (GridViewRow row in GridView1.Rows)
    {

        cmdd.Parameters.Add("@id", SqlDbType.Char, 20, "Id").Values = row.Cells["Id"].Value;
    }

    cmdd.CommandType = System.Data.CommandType.Text;

    cmdd.Parameters.AddWithValue("@profile_id", txtID.Text);
    con.Open();
    cmdd.ExecuteNonQuery();

My table should be look like this once I am able to save multiple rows from my gridview into my database:

auto_id | Id | profile_id
1       |111 | 101
2       |222 | 101
3       |333 | 101

What am I missing? I'm using asp.net with C#.

1 Answer 1

1

The error which you are getting because of, you are using Values but actually it's Value. So try this

foreach (GridViewRow row in GridView1.Rows)
{
   cmdd.Parameters.Add("@id", SqlDbType.Char, 20, "Id").Value = row.Cells[0].Value;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi thanks for replying, I have tried your code but it gives me an error at row.Cells["Id"]. It says "the best overloaded method match for 'System.Web.UI.WebControls.TableCellCollection.this[int]' has some invalid arguments". Thanks again
@user2388316 ok, So you need to pass the index of the column Id instead of name "id". I have updated my answer.I am assuming that Id is the first column that's why I have used Cells[0].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.