2009-02-23 109 views
0

当我试图显示结果在使用LINQ的gridview我得到这个错误信息。“DataSource和DataSourceID都定义在'GridView1'。删除一个定义。”我不知道该怎么办?这里是我的代码gridview与LINQ中的问题

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

您在GridView1为 “LinqDataSource1” 的标记设置DataSourceID属性。将网格绑定到在GridView后面声明的LinqDataSource。然后,在ShowEmployee()中,将代码中的DataSource属性设置为该代码,该代码将网格绑定到该方法中的查询。你不能这样做。如果您打算在代码中绑定,请删除标记中的DataSourceID。

0

如果要使用C#代码初始化数据集,请清除网格设计时的DataSourceID属性。我更喜欢这种方法。在其他情况下,不要在运行时初始化数据集。