Pages

Monday, May 20, 2013

How to SELECT a specific row of data from a Data Table using a condition in ASP.NET

To retrieve a Data Row as per a filter condition you can use the SELECT method of Data Table. The SELECT method returns an array of all DataRow that match the filter condition. The SELECT method returns DataRow object. For Example,


var user = Users.Select("UserName='" + txtUsrname.Text.Trim() + "'");
The above example, "Users" is the Data Table, and trying to get the specific user as per your input on txtUsrname text field. For instance, if you want to check a particular user is already exist or not, first load all the users to a Data Table and filter the users table using the SELECT method, and check the array length using "if" condition. For example

DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Users.xml"));
DataTable Users = DS.Tables[0];
var user = Users.Select("UserName='" + txtUsrname.Text.Trim() + "'");
if (user.Length != 0)
{
 lblresult.ForeColor = System.Drawing.Color.Red;
 lblresult.Text = "User "+txtUsrname.Text + " Already exist";
 return;
}

No comments:

Post a Comment