| Snippet | Database | C# | Visual Studio | .NET 1.1 |
SummaryControlling the data you add to datagrids can be one of the most cumbersome and annoying things you'll do in ASP.NET, but here I present how simple it can be to add basic text or link columns. This is a great starting point if you are new to DataGrids. With a little work, you'll find the datagrid is an extremely powerful tool.
Keep your eye out for .NET 2.0 where this is all simplified dramatically. |
| For the following example, drag a DataGrid control onto your ASP.NET page named DataGrid1. Then call the following method from the Page_Load event handler. |
Snippet 1: Adding BoundColumn and HyperLinkColumn to DataGridpublic void TestHyperLinkColumn()
{
BoundColumn nameColumn = new BoundColumn();
nameColumn.DataField = "ProductName";
nameColumn.DataFormatString = "{0}";
nameColumn.HeaderText = "Product";
HyperLinkColumn linkColumn = new HyperLinkColumn();
linkColumn.DataTextField = "ProductName";
linkColumn.DataTextFormatString = "{0} Details";
linkColumn.DataNavigateUrlField = "ProductID";
linkColumn.DataNavigateUrlFormatString = "/MyApp/ProductDetails.aspx={0}";
linkColumn.HeaderText = "Details";
BoundColumn blinkColumn = new BoundColumn();
blinkColumn.DataField = "ProductID";
blinkColumn.DataFormatString = "<a href='/MyApp/ProductDetails.aspx={0}'>Details</a>";
blinkColumn.HeaderText = "Details";
DataGrid1.Columns.Add(nameColumn);
DataGrid1.Columns.Add(linkColumn);
DataGrid1.Columns.Add(blinkColumn);
DataGrid1.AutoGenerateColumns = false;
DataTable dt = GetNorthwindProductTable();
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
}
|
| Note that I added three columns. The first was a simple text column (BoundColumn) with the product name. For the second column I added a link to a product details page using the HyperLinkColumn. For the third column I showed an alternate way of adding a link column if the link text can be the same for all rows, such as "Details". Just added the HTML link tag as text to the BoundColumn. It will be rendered as an HTML link when you view the page. |
|