如果它为null或为空,如何使用DataRow并在文本框中显示0 [英] How to Use DataRow and display 0 in a text box if it is null or empty

查看:99
本文介绍了如果它为null或为空,如何使用DataRow并在文本框中显示0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数据库中的表读取数据.如果表中的该字段为
为空或为null,则其在文本框txtPreviousbalance中应显示为"0".
这是我所做的,但无法正常工作.我该怎么办?

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?

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();
}

推荐答案

有很多方法可以解决此问题.这是一个:

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

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



请注意,您的代码应实际读取如下内容:



Note that your code should actually read something like:

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



SqlCommand.ExecuteReader方法 [



SqlCommand.ExecuteReader Method[^]

Again, change to suit.


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


您可以使用不同的外观:-


u can uses different ways look:-

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





while (dr2.Read())
        {
txtPreviousbalance.Text =dr2["currentbalance"]==null ? "0" : dr2["currentbalance"].ToString()
}



您也可以在查询中将"0"设置为"
"
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";


这篇关于如果它为null或为空,如何使用DataRow并在文本框中显示0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆