条件不为空的地方

时间:2017-05-06 19:17:37

标签: c# sql-server

我使用的是名为Connection的小组。

这是我的班级代码:

public static string Username;

然后在我的主窗口中的某个地方,我在数据网格视图中搜索并使用Connection.Username

我想在我的SqlDataReader搜索

中进行设置
where Username = Connection.username 

但仅限于此不为空。

这是我的主要代码:

SqlDataAdapter sda = new SqlDataAdapter("select UserName from CustomerTrans  where UserName='"+Connection.Username+"'" , con);

DataTable dt = new DataTable();
sda.Fill(dt);

dataGridView1.Rows.Clear();

foreach (DataRow item in dt.Rows)
{
    int n = dataGridView1.Rows.Add();
    dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
}

我希望避免Connection.Username为null时返回所有结果的情况。

1 个答案:

答案 0 :(得分:0)

您只需在表达式之前添加一个简单的if语句。

if(Connection.Username!=null){
 SqlDataAdapter sda = new SqlDataAdapter("select UserName from CustomerTrans  where UserName='"+Connection.Username+"'" , con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            dataGridView1.Rows.Clear();
            foreach (DataRow item in dt.Rows)
            {
                int n = dataGridView1.Rows.Add();
                dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
            }
}
相关问题