2011-09-22 100 views
2

我有一個使用LINQ to SQL顯示數據庫數據的gridview。ASP.NET添加列到Gridview

AssetDataContext db = new AssetDataContext(); 
equipmentGrid.DataSource = db.equipments.OrderBy(n => n.EQCN); 

我需要在girdview的末尾添加一列,該列有編輯/刪除/查看行的鏈接。我需要鏈接爲「http://localhost/edit.aspx?ID =」+ idOfRowItem。

+0

你需要這個:http://www.codeproject.com/KB/aspnet/create_template_columns.aspx –

回答

3

嘗試增加一個TemplateField到你的GridView像這樣:

<Columns> 
    <asp:TemplateField> 
     <ItemTemplate> 
      <a href="http://localhost/edit.aspx?ID=<%# DataBinder.Eval(Container.DataItem, "id") %>">Edit</a> 
     </ItemTemplate> 
    </asp:TemplateField> 
</Columns> 

在你可以把你喜歡的任何鏈接並綁定您從數據源希望他們的任何數據的項目模板。在上面的例子中,我剛剛從名爲id的列中提取值。

由於事實表明,這將工作得很好,但是上面的列將在GridView中最左邊對齊,並且所有自動生成的列都在右邊。

爲了解決這個問題,你可以添加一個處理程序RowCreated事件和列移動到汽車的右像這樣生成列:

gridView1.RowCreated += new GridViewRowEventHandler(gridView1_RowCreated); 

... 

void gridView1_RowCreated(object sender, GridViewRowEventArgs e) 
{ 
    GridViewRow row = e.Row; 
    TableCell actionsCell = row.Cells[0]; 
    row.Cells.Remove(actionsCell); 
    row.Cells.Add(actionsCell); 
} 

希望這有助於。