Click here to Skip to main content
15,908,776 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to read data from a table in my db. If that field in the table is
empty or null than it should display "0" in the textbox txtPreviousbalance.
Here is what I did but it is not working. What should I do?

SQL
SqlCommand cmd = new SqlCommand();
string sqlQuery2 = null;
sqlQuery2 = "select currentbalance from tblstudentfeesdetails where studentid='" + cboStudentid4.Text + "' order by dateofpayment desc";

cmd.Connection = conn;
cmd.CommandText = sqlQuery2;
cmd.CommandType = System.Data.CommandType.Text;

conn.Open();
SqlDataReader dr2 = null;
dr2 = cmd.ExecuteReader();

if (dr2.Read() == null)
{
	txtPreviousbalance.Text = "0";
}

if (conn.State != ConnectionState.Closed)
{
	conn.Close();
}
Posted
Updated 17-Jun-12 19:38pm
v4

There are a number of ways to tackle this. Here is one:

C#
if (string.IsNullOrEmpty(dr2.Read()))
{
	txtPreviousbalance.Text = "0";
}


Note that your code should actually read something like:

C#
while(dr2.Read())
{
   txtPreviousbalance.Text = string.IsNullOrEmpty(dr2.GetString(0)) ? "0" : dr2.GetString(0);
}


SqlCommand.ExecuteReader Method[^]

Again, change to suit.
 
Share this answer
 
Comments
Vani Kulkarni 18-Jun-12 1:09am    
My 5! Nicely answered.
in place of
C#
if (dr2.Read() == null)
{
    txtPreviousbalance.Text = "0";
}

u can uses different ways look:-
C#
if (dr2 == null)
{
    txtPreviousbalance.Text = "0";
}</


SQL
while (dr2.Read())
        {
txtPreviousbalance.Text =dr2["currentbalance"]==null ? "0" : dr2["currentbalance"].ToString()
}
 
Share this answer
 
v2
Hi,
You can also set "0" in Query like

sqlQuery2 = "select Case currentbalance When NULL 0 Else currentbalance End as currentbalance from tblstudentfeesdetails where studentid='" + cboStudentid4.Text + "' order by dateofpayment desc";
 
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