Sam
Sam

Reputation: 303

How to find index of controls in flowlayoutpanel in C#

I am new to C#.

I have Form1 and flowlayoutpanel. I dynamically add Buttons to flowlayoutpanel and the buttons details comes from a database table.

I want to know the name of the first button in the flowlayoutpanel.

for (i = 0; i < DataTable.Rows.Count; i++)
        {

          Button btn = new Button();
          btn.Name = DataTable.Rows[i]["Name"].ToString();
          btn.Text = DataTable.Rows[i]["PostCode"].ToString();
          flowlayoutpanel.Controls.Add(btn);
        }            

       String First_Button_Name = ........... 

Upvotes: 0

Views: 2001

Answers (2)

MineR
MineR

Reputation: 2194

If you want to get the name of the first button to be added to the FlowLayoutPanel, regardless of how those buttons got there, use:

 string firstButtonName = flowlayoutpanel.Controls.OfType<Button>().FirstOrDefault()?.Name;

Upvotes: 1

Lajos Arpad
Lajos Arpad

Reputation: 76434

This is the value you are searching for:

DataTable.Rows[0]["Name"].ToString()

but make sure you have at least an element before you try to get this value.

Upvotes: 0

Related Questions