如何使我的 id 声明全局或从其他方法获取它
本文关键字:其他 方法 获取 全局 何使 我的 id 声明 | 更新日期: 2023-09-27 18:35:58
大家好,我有这个代码:我宣布这个全局:
FlowLayoutPanel PresPanel = new FlowLayoutPanel();
我的初始化面板 :
Label PresLabel = new Label();
PresLabel.Text = "PRESIDENT :";
PresLabel.AutoSize = true;
PresLabel.Location = new Point(30, 20);
PresLabel.Font = new Font(this.Font, FontStyle.Bold);
PresLabel.Font = new Font("Courier New", 18);
PresLabel.ForeColor = Color.Orange;
this.Controls.Add(PresLabel);
PresPanel.Size = new Size(630, 160);
PresPanel.Location = new Point(50, 50);
PresPanel.FlowDirection = FlowDirection.LeftToRight;
PresPanel.BorderStyle = BorderStyle.FixedSingle;
PresPanel.AutoScroll = true;
PresPanel.WrapContents = false;
Controls.Add(PresPanel);
Form_load :
InitPanel();
PresPanel.SuspendLayout();
BtnVote.CenterHorizontally();
try
{
string cmdText = "SELECT (FirstName + ' ' + MiddleName + ' ' + LastName) as FullName, " +
"imgPath as ImagePath, " + "id as GetID 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.GetInt32(2));
}
reader.Close();
sc.Close();
PresPanel.ResumeLayout(true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
我的添加单选按钮 :
public void AddRadioButton(string fullName, string imagePath, int getID)
{
RadioButton radio = new RadioButton { Text = fullName, Parent = PresPanel };
radio.AutoSize = false;
radio.Size = new Size(150, 130);
radio.Image = new Bitmap(Image.FromFile(imagePath), 90, 90);
radio.TextImageRelation = TextImageRelation.ImageAboveText;
radio.CheckAlign = ContentAlignment.BottomCenter;
radio.CheckAlign = ContentAlignment.BottomCenter;
radio.ImageAlign = ContentAlignment.MiddleCenter;
radio.TextAlign = ContentAlignment.MiddleCenter;
radio.ForeColor = Color.LimeGreen;
radio.CheckedChanged += radio_CheckedChanged;
}
现在对于我的问题,每当我单击每个单选按钮时,如何从 AddradioButton 获取我的 getID?谢谢。。:)
您可以使用 Tag
属性:
public void AddRadioButton(string fullName, string imagePath, int getID)
{
RadioButton radio = new RadioButton { Text = fullName, Parent = PresPanel };
//.....
radio.Tag = getID;
radio.CheckedChanged += radio_CheckedChanged;
}
//then in the CheckedChanged event handler
private void radio_CheckedChanged(object sender, EventArgs e){
RadioButton radio = sender as RadioButton;
int getID = (int) (radio.Tag ?? -1);//suppose -1 is an invalid ID which is used to indicate that there is not associated ID
//other code....
}