-2

I'm using a class named Connection.

Here is my class code:

public static string Username;

Then somewhere in my main windows form I'm searching in a datagridview and I use Connection.Username.

I want to set in my SqlDataReader do search

where Username = Connection.username 

but only in case that this is not null.

Here is my main code:

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

I want to avoid the case when Connection.Username is null to return all results.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dim
  • 97
  • 2
  • 9
  • 5
    `if (Username != null)`? – BJ Myers May 06 '17 at 19:20
  • http://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work – Wiktor Zychla May 06 '17 at 19:22
  • Sql Server null and C# null are two different concepts. Null in SQL Server means the i-do-not-know rather than not existing. So make that part of the query called in TSQL rather than in your application per se – clifton_h May 07 '17 at 01:32

1 Answers1

0

You can just add a simple if statement before your expressions.

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();
            }
}
osumatu
  • 410
  • 1
  • 8
  • 25
  • What if in case i have more than one where condition.Example Username,Children.....??? – Dim May 06 '17 at 19:34
  • Then add them to the if statement with && (and) operation. Like if((Connection.Username!=null) && (Connection.Children!=null)) etc. – osumatu May 06 '17 at 19:41