views:

204

answers:

1

Hi all, when i am trying to display result in gridview using LINQ i am getting this error message."Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition." i am not getting any clue what to do? Here is my code

protected void SelectBtn_Click(object sender, EventArgs e)
{
    ShowEmployee();
}
private void ShowEmployee()
{
    DataClassesDataContext db = new DataClassesDataContext();
    var name = from E in db.Employees
               orderby E.Age ascending
               select E;
    GridView1.DataSource = name;
    GridView1.DataBind();        
}
protected void InsertBtn_Click(object sender, EventArgs e)
{
    int id = Convert.ToInt32(TxtId.Text);
    string name = TxtName.Text;
    string address = TxtAddress.Text;
    int age = Convert.ToInt32(TxtAge.Text);
    DataClassesDataContext db = new DataClassesDataContext();
    try
    {
        Employee emp = new Employee { EmployeeId = id, Name = name, Address = address, Age = age };
        db.Employees.InsertOnSubmit(emp);
        db.SubmitChanges();
        LblMessage.Text = "Employee has been added successfully";
        TxtId.Text = "";
        TxtName.Text = "";
        TxtAddress.Text = "";
        TxtAge.Text = "";
        ShowEmployee();
    }
    catch (Exception ee)
    {
        LblMessage.Text = ee.Message.ToString();
    }       
}
protected void UpdateBtn_Click(object sender, EventArgs e)
{
    string name=TxtName.Text;
    string address=TxtAddress.Text;
    DataClassesDataContext db = new DataClassesDataContext();
    Employee emp = db.Employees.FirstOrDefault(E => E.Name.StartsWith(name));
    emp.Address = address;
    db.SubmitChanges();
    ShowEmployee();
}
protected void DeleteBtn_Click(object sender, EventArgs e)
{
    DataClassesDataContext db = new DataClassesDataContext();
    Employee emp = db.Employees.Single(E => E.Address.StartsWith("Delhi"));
    db.Employees.DeleteOnSubmit(emp);
    db.SubmitChanges();
    ShowEmployee();
}

+1  A: 

You set the DataSourceID property in the markup of GridView1 to "LinqDataSource1". That binds the grid to the LinqDataSource declared just after the GridView. Then in ShowEmployee() you set the DataSource property in code, which binds the grid to the query in that method. You can't do both. Remove the DataSourceID in markup if you intend to bind in code.

quinnapi