Saturday, 4 June 2011

C# Code to get value by key or id from a database table


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