Reputation: 163
Hello Everyone, I am having trouble in getting the vote count of my voting system. Whenever I click a radiobutton, I have to get the ID of that candidate and pass it to the other form to make a vote count. I am having trouble in making an event handler too. All of my controls are dynamic.
I have this code so far:
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;
}
}
Thanks :)
Upvotes: 1
Views: 840
Reputation: 3798
You can define common checkchange event for all your dynamic radio button like this
RadioButton radio = new RadioButton {Text = fullName, Parent = panel};
radio.CheckedChanged += radio_CheckedChanged;
radio.Tag=1; //you can set here your own object.
Handle this event like this
void radio_CheckedChanged(object sender, EventArgs e)
{
var radio=(RadioButton)sender;
int id=(int)radio.Tag; //cast your object here
}
Hope this helps
Upvotes: 1