views:

187

answers:

2

Hi all, I want to display all the data in gridview which i am inserting in runtime. For that i have written code but getting this error.

"Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition."

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindData();
    }
}

public void BindData()
{
     string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
     SqlConnection con = new SqlConnection(str);
     SqlDataAdapter da = new SqlDataAdapter("select * from Items where ItemId='" + TxtItemId.Text + "'", con);
     DataSet ds = new DataSet();
     da.Fill(ds,"Items");
     GridView1.DataSource = ds;         
     GridView1.DataBind();
}

Pls modify my code where is my mistake.

Thanks, Sumit

A: 

The two properties are mutually exclusive (when you use one of them, you are not allowed to use the other one):

  1. The DataSourceID property is to be used with a DataSource control (ObjectDataSource, XmlDataSource, SqlDataSource, etc)
  2. The DataSource property is to be used with custom objects / custom data binding.

Examples:

  1. DataSourceId

    @asp:ObjectDataSource ID="ods1" runat="server" SelectMethod="Test" TypeName="TestBL" /@ @asp:GridView ID="gv1" runat="server" DataSourceID="ods1" /@

in this case databinding occurs automatically

  1. DataSource

    @asp:GridView ID="gv2" runat="server" %@

and in code behind you would have something like this:

overrides void OnLoad(..)
{
    List<DataObject> source = new List<DataObject>();
    source.Add(new DataObject(..));
    source.Add(new DataObject(..));
    source.Add(new DataObject(..));
    gv2.DataSource = source;
    gv2.DataBind();
}

Please note that I have used @ instead of angular brackets.

Bogdan Maxim
not clear with your answer would you be pls more specific. I am using sqlserver2000 database. From gridview create new connection option just selected the tables. After that i have written this code in code behind page.
A: 

It seems like you want to bind your datasource manually. Remove the DataSourceID property at the design view from your gridview. It should be something like that :

<asp:GridView runat="server" ID="grid" DataSourceID="SqlDataSource1"></asp:GridView>

Just remove the DataSourceID="SqlDataSource1" property.

Canavar
No....my requirement is i will add some data from text box and after clicking on add button it should immediately reflect to the gridview. And above my code for this.
But, you can't merge your data with different datasources, try to use DataBinding at first request and at second request, try to merge your data sources.
Canavar
Are you using two datasources?
Bogdan Maxim