Gridview OnItemDataBound Event Example

How to access Datatable Row inside Gridview OnItemDataBound Event

October 14, 2020

In this article we will cover how to bind gridview using Datatable and access Datatable Row inside Gridview OnItemDataBound Event.

We will also cover how to FindControl like panel, hidden field and apply if else condition and assign value inside Gridview OnItemDataBound Event.

<asp:Repeater runat="server" ID="rptblogs" OnItemDataBound="rptblogs_ItemDataBound">
    <ItemTemplate>
        <h1><%#Eval("Name"%></h1>
        <p><%#Eval("Description"%></p>
 
        <asp:Panel ID="pnlImage" runat="server" Visible="false">
            <img src="<%#Eval("BannerImage"%>" />
        </asp:Panel>
 
        <asp:Panel ID="pnlVideo" runat="server" Visible="false">
            <iframe src="<%#Eval("VideoLink"%>"></iframe>
        </asp:Panel>
 
        <asp:HiddenField ID="hdn_blogid" runat="server" />
    </ItemTemplate>
</asp:Repeater>
using (SqlConnection con = new SqlConnection("connection_string"))
{
    using (SqlCommand cmd = new SqlCommand("select * from blogs"con))
    {
        cmd.CommandType = CommandType.Text;
        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
        {
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);
                rptblogs.DataSource = dt;
                rptblogs.DataBind();
            }
        }
    }
}
protected void rptblogs_ItemDataBound(object senderRepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        RepeaterItem item = e.Item;
 
        DataRowView drv = e.Item.DataItem as DataRowView;
 
        if (drv.Row["type"].ToString() == "image")
            (item.FindControl("pnlImage"as Panel).Visible = true;
        else
            (item.FindControl("pnlVideo"as Panel).Visible = true;
 
        (item.FindControl("hdn_blogid"as HiddenField).Value = drv.Row["Blog_ID"].ToString();
    }
}

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...