Reputation: 785
I couldn't figure out why i am having problem in
btn.Text = comando.ExecuteScalar().ToString() ;
statement. If someone explains why i am having a problem( i am a newbie by the way) and how can i correct it. Thanks.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SqlCommand comando = new SqlCommand();
SqlConnection conn = new SqlConnection(@"server=.\SQLEXPRESS;Initial Catalog=try;Integrated Security=True;Pooling=False");
comando.Connection = conn;
conn.Open();
int NumOfButtons = 12;
int loc = 20;
int k = 5;
for (int i = 1; i <= NumOfButtons; i++)
{
Button btn = new Button();
ListBox lst = new ListBox();
{
lst.Location = new Point(4, 4);
btn.Size = new Size(60, 20);
btn.Tag = i;
comando.CommandText = "select ProductName from Products where productID = " + btn.Tag;
btn.Text = comando.ExecuteScalar().ToString() ; // here error occurs why?
btn.Location = new Point(k, loc);
}
loc += 20;
if (i > 6)
{
if (loc == 160)
{
loc = 20;
}
k = 65;
btn.Location = new Point(k, loc);
}
panel1.Controls.Add(btn);
}
}
Upvotes: 0
Views: 208
Reputation: 785
the problem was i used a character in the sql statment that is not in the English alphabets. but in my question i did not copy and paste the exact statement. thus when i corrected it, its done. but here i want to thank to all of u because i learned more from your answers. THANKS a lot. i all rated you up and just accepted devio's answer for informing more. He stated the possible problems. can be helpful for newbies like me.
Upvotes: 0
Reputation: 1127
Try this,
ListBox lst = new ListBox();
{
try
{
lst.Location = new Point(4, 4);
btn.Size = new Size(60, 20);
btn.Tag = i;
comando.CommandText = "select ProductName from Products where productID = " + btn.Tag;
btn.Text = comando.ExecuteScalar().ToString() ; // here error occurs why?
btn.Location = new Point(k, loc);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
now execute you app to see what your app have to say regarding the exception.
Upvotes: 1
Reputation: 37215
We don't know what kind of exception you get, so it might be any of
Products
Products
does not have the columns ProductName
or productId
Products
table is missing at least one record with productID's 1 to 12.ProductName
column is NULL
for one of the selected recordsUpvotes: 2