The Requirement
In any application, sometimes it is required to retrieve a value from the database by passing an Id. For example, you want to get the name of the student whose rollno is 32. For this purpose we can use a single method that will retrieve the reqiuired data from any table.
protected void Page_Load(object sender, EventArgs e)
{
string studentname = GetValueById("TblStudents", "S001", "sid", "sname");
Response.Write(studentname);
}
public string GetValueById(string TableName, string Id, string IdColumnName, string ValueColumnName)
{
try
{
string query, result;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ToString());
query = "SELECT " + ValueColumnName + " FROM " + TableName + " WHERE " + IdColumnName + " = '" + Id + "'";
SqlCommand com = new SqlCommand(query, con);
con.Open();
result = Convert.ToString(com.ExecuteScalar());
if (result == "")
{
result = "Not Found";
}
con.Close();
return result;
}
catch (Exception ex)
{
return ex.Message;
}
}
No comments:
Post a Comment