Saturday, 4 June 2011

C# code to check the existence of an item in a Database Table using a single method


The Requirement

In any application, sometimes it is required to check if a particular value exists in a Database table or not. For example, you want to check if an user with user id U001 exists in the database or not. For this purpose we can use a single method that will check for the existence of a particular value from a particular table.

protected void Page_Load(object sender, EventArgs e)
{
        bool result = CheckExist("TblStudents", "sid", "S001");
        Response.Write("Result: " + result.ToString());
}

public bool CheckExist(string TableName, string ColumnName, string Value)
{
        string query, result;
        bool IsExists;
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ToString());
        query = "SELECT " + ColumnName + " FROM " + TableName + " WHERE " + ColumnName + " = '" + Value + "'";
        SqlCommand com = new SqlCommand(query, con);
        con.Open();
        result = Convert.ToString(com.ExecuteScalar());
        if (result != "")
            IsExists = true;
        else
            IsExists = false;
        con.Close();
        return IsExists;
}

No comments:

Post a Comment