如何使用我在 C# winforms 中的代码从数据库中获取 ID

本文关键字:代码 数据库 获取 ID winforms 何使用 | 更新日期: 2023-09-27 18:35:21

大家好,我在获取投票系统的票数时遇到问题。每当我单击单选按钮时,我都必须获取该候选人的 ID 并将其传递给另一个表单才能计算选票。我在制作事件处理程序时也遇到了麻烦。我所有的控件都是动态的。

到目前为止,我有这段代码:

    public partial class Form1 : Form {
    public Form1()
    {
        InitializeComponent();
        Load += Form1_Load;
    }
    FlowLayoutPanel panel = new FlowLayoutPanel();
    private void InitPanel()
    {
        panel.Size = new Size(600, 150);
        panel.Location = new Point(50, 50);
        panel.FlowDirection = FlowDirection.LeftToRight;
        panel.AutoScroll = true;
        panel.WrapContents = false;
        Controls.Add(panel);
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        InitPanel();
        panel.SuspendLayout();
        string cmdText = "SELECT (FirstName + ' ' + MiddleName + ' ' + LastName) as FullName, " +
             "imgPath as ImagePath FROM TableVote WHERE Position='President'";
        using(SqlCommand com = new SqlCommand(cmdText,sc))
        {
            if(sc.State != ConnectionState.Open) sc.Open();
            SqlDataReader reader = com.ExecuteReader();       
            while(reader.Read()){
            AddRadioButton(reader.GetString(0), reader.GetString(1));
        }
        reader.Close();
        sc.Close();
        panel.ResumeLayout(true);
      }
   }
   private void AddRadioButton(string fullName, string imagePath)
   {
        RadioButton radio = new RadioButton {Text = fullName, Parent = panel};
        radio.AutoSize = true;
        radio.Image = new Bitmap(Image.FromFile(imagePath),75,75);
        radio.TextImageRelation = TextImageRelation.ImageAboveText;    
        radio.CheckAlign = ContentAlignment.BottomCenter;   
    }
   }

谢谢:)

如何使用我在 C# winforms 中的代码从数据库中获取 ID

您可以像这样为所有动态单选按钮定义通用检查更改事件

 RadioButton radio = new RadioButton {Text = fullName, Parent = panel};
 radio.CheckedChanged += radio_CheckedChanged;
 radio.Tag=1;  //you can set here your own object.

像这样处理此事件

void radio_CheckedChanged(object sender, EventArgs e)
    {
       var radio=(RadioButton)sender;
       int id=(int)radio.Tag;  //cast your object here 
    }

希望这有帮助