我的数据库中有一个表的多个列。我想检查某个列是否有空值。我使用了这段代码,但它只适用于第一个,而不是第二个。
if (!read.IsDBNull(3))
{
lblInc3.Visible = true;
txtInc3.Visible = true;
lblInc3.Text = read["Income3"].ToString();
}
else if (!read.IsDBNull(4))
{
lblInc4.Visible = true;
txtInc4.Visible = true;
lblInc4.Text = read["Income4"].ToString();
}
else
{
txtInc3.Visible = false;
txtInc4.Visible = false;
}
如果多列没有空值,我只想执行逻辑。如果它有空值,那么文本框不应该是可见的。
编辑:
try
{
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
sqlCon.Open();
SqlCommand com = new SqlCommand("SELECT * FROM Allowance", sqlCon);
SqlParameter income1 = new SqlParameter("@Income1", SqlDbType.VarChar, 20);
com.Parameters.Add(income1);
income1.Direction = ParameterDirection.Output;
SqlParameter income2 = new SqlParameter("@Income2", SqlDbType.VarChar, 20);
com.Parameters.Add(income2);
income2.Direction = ParameterDirection.Output;
SqlParameter income3 = new SqlParameter("@Income3", SqlDbType.VarChar, 20);
com.Parameters.Add(income3);
income3.Direction = ParameterDirection.Output;
SqlParameter income4 = new SqlParameter("@Income4", SqlDbType.VarChar, 20);
com.Parameters.Add(income4);
income4.Direction = ParameterDirection.Output;
SqlParameter income5 = new SqlParameter("@Income5", SqlDbType.VarChar, 20);
com.Parameters.Add(income5);
income5.Direction = ParameterDirection.Output;
SqlDataReader read = com.ExecuteReader();
while (read.Read())
{
bool threeBool = !read.IsDBNull(1) ? true : false;
lblInc1.Visible = threeBool;
txtInc1.Visible = threeBool;
lblInc1.Text = threeBool ? read["Income1"].ToString() : string.Empty;
bool fourBool = !read.IsDBNull(4) ? true : false;
lblInc4.Visible = fourBool;
txtInc4.Visible = fourBool;
lblInc4.Text = fourBool ? read["Income4"].ToString() : string.Empty;
/*if (!read.IsDBNull(1))
{
lblInc1.Visible = true;
txtInc1.Visible = true;
lblInc1.Text = read["Income1"].ToString();
}
else
{
txtInc1.Visible = false;
}
if (!read.IsDBNull(2))
{
lblInc2.Visible = true;
txtInc2.Visible = true;
lblInc2.Text = read["Income2"].ToString();
}
else
{
txtInc2.Visible = false;
}
if (!read.IsDBNull(3))
{
lblInc3.Visible = true;
txtInc3.Visible = true;
lblInc3.Text = read["Income3"].ToString();
}
else
{
txtInc3.Visible = false;
}
if (!read.IsDBNull(4))
{
lblInc4.Visible = true;
txtInc4.Visible = true;
lblInc4.Text = read["Income4"].ToString();
}
else
{
txtInc4.Visible = false;
}
if (!read.IsDBNull(5))
{
lblInc5.Visible = true;
txtInc5.Visible = true;
lblInc5.Text = read["Income5"].ToString();
}
else
{
txtInc5.Visible = false;
}*/
} catch (Exception ex) {
throw;
}