Click here to Skip to main content
16,015,917 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am unsure how to check if select returns any rows from database. I want to have an error message if there are no rows found

What I have tried:

C#
try
        {
            string strConnString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
            SqlConnection con = new SqlConnection(strConnString);
            DataTable dt = new DataTable();

            using (SqlConnection conn = new SqlConnection(strConnString))
            {
                string strQuery = "SELECT * FROM TDLoanRate where LoanType Like'" + txtValue.Text + "%'";
                SqlCommand cmd = new SqlCommand(strQuery);
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    conn.Open();
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                    GridView2.DataSource = dt;
                    GridView2.DataBind();
                } 
Posted
Updated 25-Jul-16 3:42am
v2
Comments

C#
int count = dt.Rows.Count; // get the count 

Your code is vulnerable to SQL injection [^] attacks.
Always use Parameterized queries to prevent SQL Injection Attacks in SQL Server[^]
 
Share this answer
 
Comments
Member 12652110 25-Jul-16 7:19am    
I am very sorry. I do not know where to insert the codes. Do you mind copying in my codes and insert them? I have only started asp.net a few months ago and do not really understand
Karthik_Mahalingam 25-Jul-16 7:26am    
sda.Fill(dt);
int count = dt.Rows.Count; // get the count
label1.Text = count.ToString(); // display it in label or anywhere...
GridView2.DataSource = dt;
GridView2.DataBind();
simply get count from particular table if count > 1 then there is record found, other wise there is no record found.
 
Share this answer
 
Comments
Member 12652110 25-Jul-16 7:02am    
can u show me an example? I do not quite understand
if i want to check is there any customer then what i will do

i will count

select count(1) from customers

store that value in any variable and check what ever condition you want.
suppose i store value in string s;
if(convert.int32(s)>0)
{

}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900