C# – Both DataSource and DataSourceID are defined on ‘GridView1’. Remove one definition

asp.netcsql

I'm using a gridview and SqlDataSource to bind the data table information to the gridview.
On gridview update event I have the following code :

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
  {
                    var ID = (int)GridView1.DataKeys[e.RowIndex]["No"];
                    string costring = "the conn string";
                    string query = "UPDATE mytable SET Age = @Age WHERE No = " + ID;
                    using (SqlConnection dataConnection = new SqlConnection(costring))
                    {
                        using (SqlCommand com = new SqlCommand(query, dataConnection))
                        {
                            dataConnection.Open();
                            int valueID = 18;
                            com.Parameters.AddWithValue("Age", valueID);
                            com.ExecuteNonQuery();
                            GridView1.DataSource = SqlDataSource1;
                            GridView1.DataBind();
                            dataConnection.Close();
                        }
                    }
                 }
  • If I click the update event I get : "Both DataSource and DataSourceID
    are defined on 'GridView1'. Remove one definition." here
    "GridView1.DataBind();"! but when I refresh the webpage the code
    worked but I always get this error.
  • I've searched on google and I found that I can't use both..but I need
    to see the information on the gridview and I can't remove the
    sqldatasource binding and also I need to make the code work.
  • I've tried DataGridviewID = null; and I don't get any error but
    nothing is changed the code is not executed..nothing happens

Best Answer

Do you really need to assign data source again if you emit this statement

  GridView1.DataSource = SqlDataSource1;
  GridView1.DataBind();

and use

  SqlDataSource1.Update();

There is an example of using datasource, i hope that will help you Datasource example

Related Topic