First let us create a sample data source for bind to the gridview.
private DataTable createDatatable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Country", typeof(string));
dt.Columns.Add("URL", typeof(string));
dt.Columns.Add("Status", typeof(string));
dt.Rows.Add("Chamara", "Sri lanaka", "http://itzonesl.blogspot.com/", "enable");
dt.Rows.Add("sam", "America", "http://itzonesl.blogspot.com/", "enable");
dt.Rows.Add("jhon", "England", "http://itzonesl.blogspot.com/", "disable");
dt.Rows.Add("cater", "Spain", "http://itzonesl.blogspot.com/", "enable");
dt.Rows.Add("amanda", "Australia", "http://itzonesl.blogspot.com/", "disable");
return dt;
}
What i need is, i wand to add a link button for the URL field and disable it for "jhon" and "amanda". The column "Status" will specify whether the link should be enabled or disabled.
Let create our gridview.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:TemplateField HeaderText="URL">
<ItemTemplate>
<asp:LinkButton ID="lbURL" runat="server" Text='<%# Eval("URL") %>' Enabled='<%# Eval("Status") != "disable" ? true : false %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
Bind data to the gridview on page load event.
private void BindGrid()
{
GridView1.DataSource = createDatatable();
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
Note the asp:TemplateField in the GridView. In the Enable property of the LinkButton we have used a "if" condition to check the "Status".
No comments:
Write comments