This code worked yesterday, but today when I start, i got this error. I dont know what happened, the database still connected.
The code:
private void LoginFS_Load(object sender, EventArgs e)
{
SQLFunctions Lgn = new SQLFunctions();
Lgn.ConnectionToday();
SqlCommand cmd = new SqlCommand();
cmd.Connection = SQLFunctions.conn;
int NumOfButtons = 50;
for (int i = 1; i <= NumOfButtons; i++)
{
Button btn = new Button();
{
btn.Tag = i;
btn.Dock = DockStyle.Fill;
btn.Margin = new Padding(10, 10, 10, 10);
cmd.CommandText = "SELECT username FROM Login where id='" + btn.Tag + "'";
btn.Text = cmd.ExecuteScalar().ToString(); // <= ERROR
//ERROR: An unhandled exception of type 'System.NullReferenceException' occurred in. Additional information: Object reference not set to an instance of an object.
string btn_name = cmd.ExecuteScalar().ToString();
btn.Name = btn_name.ToString();
btn.Click += delegate
{
pass_txt.Clear();
username_txt.Text = btn_name;
username_lbl.Text = btn_name;
username_lbl.Visible = true;
pass_txt.ReadOnly = false;
};
}
users_table.Controls.Add(btn);
}
SQLFunctions.conn.Close();
}
What should I do, or why got this error? Thanks
where id=it'd be much cleaner and more secure to use SQL parameters rather than concatenating the query string manually.Selectstatement returned 0 row which led toExecuteScalar()being null. And you get a null reference exception. *Edit: Check this MSDN post