First of all, sorry for my English :)
I would like to make buttons automatically from database. In the database, every button own an ID, and i call this ID.
My problem is simple, If one of the IDs missing (like 1,2,4,5), the program stop after the 2nd read. Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace e_res
{
public partial class Layout : Form
{
public Layout()
{
InitializeComponent();
}
private void Layout_Load(object sender, EventArgs e)
{
SQLFunctions Lgn = new SQLFunctions();
Lgn.ConnectionToday();
SqlCommand cmd = new SqlCommand();
cmd.Connection = SQLFunctions.conn;
int NumOfButtons = 40;
int i = 1;
cmd.CommandText = "SELECT id FROM Buttons where id='" + i + "'";
int _bId = Int32.Parse(cmd.ExecuteScalar().ToString());
// int counter = 0;
while ( _bId <= NumOfButtons)
{
if (_bId != null)
{
Button btn = new Button();
{
btn.Tag = _bId;
btn.Dock = DockStyle.Fill;
btn.Margin = new Padding(10, 10, 10, 10);
cmd.CommandText = "SELECT bName FROM Buttons where id='" + btn.Tag + "'";
btn.Text = cmd.ExecuteScalar().ToString();
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;
};*/
}
cmd.CommandText = "SELECT col FROM Buttons where id='" + btn.Tag + "'";
int btn_col = Int32.Parse(cmd.ExecuteScalar().ToString());
// MessageBox.Show(btn_col.ToString());
cmd.CommandText = "SELECT row FROM Buttons where id='" + btn.Tag + "'";
int btn_row = Int32.Parse(cmd.ExecuteScalar().ToString());
// MessageBox.Show(btn_row.ToString());
tableLayoutPanel4.Controls.Add(btn, btn_col, btn_row);
_bId++;
}
else
{
_bId++;
}
}
SQLFunctions.conn.Close();
}
private void button2_Click(object sender, EventArgs e)
{
NewButton nw = new NewButton();
nw.Show();
}
}
}
Thanks
select bname,col,row from buttons where id <= NumOfButtonsoutside the loop, then access the result set within a loop that terminates when there are no more rows. This will also solve your current problem.