c#如何从数据库表内读取内容并动态创建CheckBox
表名:abcd
表abcd里面有:ID,BuMen
根据BuMen的数量,动态创建CheckBox,CheckBox的text为BuMen的值
然后在写入到数据库表aa的字段bb中
还有,动态创建的CheckBox的坐标如何定义
因为grouppanel里面已经有两行控件,想放到这两行控件的下方 展开
public partial class Form1 : Form
{
private SqlConnection conn = null;
public Form1()
{
InitializeComponent();
conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\database\loginDemo\loginDemo\bin\Debug\demo.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
}
private void gpbMain_Enter(object sender, EventArgs e)
{
conn = getConnection();
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "select bumen from abcd ";
comm.CommandType = CommandType.Text;
SqlDataReader read = comm.ExecuteReader();
int x = txtMarry.Location.X;
int y = txtMarry.Location.Y;
while (read.Read())
{
y += 20;
if (gpbMain.Width < y)
{
this.Width += 20;
gpbMain.Width += 20;
}
CheckBox ch = new CheckBox();
ch.Location = new Point(x, y);
ch.Text = read.GetString(0).ToString();
gpbMain.Controls.Add(ch);
}
if (conn != null)
{
conn.Close();
conn.Dispose();
}
}
private SqlConnection getConnection()
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
return conn;
}
}
}
数据库就是一个Id,bumen.
{
private SqlConnection conn = null;
public Form1()
{
InitializeComponent();
conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\database\loginDemo\loginDemo\bin\Debug\demo.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
}
private void gpbMain_Enter(object sender, EventArgs e)
{
conn = getConnection();
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "select bumen from abcd ";
comm.CommandType = CommandType.Text;
SqlDataReader read = comm.ExecuteReader();
int x = txtMarry.Location.X;
int y = txtMarry.Location.Y;
while (read.Read())
{
y += 20;
if (gpbMain.Width < y)
{
this.Width += 20;
gpbMain.Width += 20;
}
CheckBox ch = new CheckBox();
ch.Location = new Point(x, y);
ch.Text = read.GetString(0).ToString();
gpbMain.Controls.Add(ch);
}
if (conn != null)
{
conn.Close();
conn.Dispose();
}
}
private SqlConnection getConnection()
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
return conn;
}
}
}