How to disable link button in data list control based on condition in run time?
In this article I am going to explain about how to disable data list column link button based on some conditions at run time. This code snippet is may be help you in your project time check this explanation and code.
Description
Most of them asking in grid view or data list control I want to disable row or link button based on condition. Same like that requirement I have write code in the DataList ItemDataBound event to check the condition like salary is less than 13,000 then I disable the link button and if salary is greater than 13,000 to enable that link button.
Refer below code for the same to disable link button and also use this code to disable button or label or anyother control to enable / disable based on your requirement. Full Source
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da;
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadDt();
}
}
void LoadDt()
{
sqlcon.Open();
sqlcmd = new SqlCommand("select * from emp", sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
sqlcon.Close();
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string sal = string.Empty;
DataRowView dr = (DataRowView)(e.Item.DataItem);
sal = (string)dr.Row["sal"].ToString();
//i disable link button only when salary less than 13000 -- change this code as per requirement
if (sal != "")
{
if (Convert.ToDouble(sal) < 13000)
{
LinkButton lnkbtn = (LinkButton)e.Item.FindControl("lnkbtn");
lnkbtn.Enabled = false;
}
}
}
}
}Output
Source Code
Here I attached full source code. Download it and test it.
Client Side: ASP.NET
Code Behind : C#Conclusion
I hope this source code is help you to know about disable controls in data list.