优秀的编程知识分享平台

网站首页 > 技术文章 正文

C#中通过数据库动态生成RadioButton组

nanyue 2025-03-13 18:39:31 技术文章 2 ℃

有一个切换仓库的需求,仓库名称是保存在数据库中的,需要通过RadioButton组来实现仓库的单选,绑定数据很简单,主要是怎么实现行列的排布,因为是动态生成的,肯定无法手动拖控件来排列了。

我们需要先拖一个panel,然后RadioButton就放在这个panel中,需要考虑的因素有每行显示几个RadioButton,行与行的间距是多少,列之间的间距是多少,RadioButton宽度等,如果它足够宽那么就不需要设置列间距了。

从数据库中读取仓库的名称并转换成字符串数组,GetTable是返回一个DataTable

string[] S1 = jxc.GetTable("select 名称 from 商品仓库 order by id desc ").AsEnumerable().Select(d => d.Field("名称")).ToArray();

设置好每行几个,间距和大小,创建RadioButton数组

 int top =30; //行间距
 int radioWidth =150; //宽度
 int n = 0;
 int row = 3;//每行的数量
	RadioButton[] rb=new RadioButton[S1.Length+1];

对控件数据进行位置排列,排成我们想要的,这里是按行来生成的,需要注意的是第一行属于特殊情况,需要单独处理一下,不然的话会重叠在一起的。

for (int i = 0; i < S1.Length; i++) 
{
    int x, y;
    if (i % row == 0)
    {
        if (n == 0 && i<row)
        {
            n = 0;
        }
        else 
        {
            n = n + 1;
        }
       
        x = (i% row) * radioWidth + 10;
        y = top*n+10;
    }
    else 
    {
        if (i == 0)
        {
            x = 10;
        }
        else 
        {
            x = (i % row) * radioWidth + 10;
        }
        y = top*n+10;
    }
    rb[i] = new RadioButton();
    rb[i].AutoSize = true;
    rb[i].Top = top;
    rb[i].Location = new Point(x, y); //控件左上角相对于容器左上角的坐标,以及每个控件之间的距离
    rb[i].Text = S1[i].ToString();
    rb[i].Visible = true;
    rb[i].Name = "RB" + i;
    this.panel1.Controls.Add(rb[i]);

}

不同参数下的效果图,此处用商品名称代替下仓库名称

行间距30,宽度150,每行3列

行间距30,宽度150,每行5列

行间距50,宽度150,每行5列

行间距30,宽度300,每行3列

为RadioButton数组增加选择改变的事件,选择后直接把文本显示在仓库名称文本框中

 foreach (RadioButton r in rb) 
 {
     r.CheckedChanged += new EventHandler(R_CheckedChanged);
 }
private void R_CheckedChanged(object sender, EventArgs e)
{
    RadioButton radioButton = (RadioButton)sender;
    txt_name.Text = radioButton.Text;
}

好了,就到此结束了,如果对你有帮助,欢迎交流!

最近发表
标签列表