如何修复C# WinForm中‘无法将方法组Focus转换为非委托类型int’错误
Hey there, let's work through this issue together!
Why You're Getting That Error
The error Cannot convert method group 'Focus' to non-delegate type 'int' comes from two key mistakes in your code:
- Your
tst1variable is hardcoded to0and has no link to the currently active tab page. Tabp1.Focusis a method (it returns a boolean indicating if focus was set), not an integer value. You can't use a method as a case condition when switching on an int.
Correct Implementation: Target the Active Tab
To make your save button only act on the tab the user is currently viewing, you need to use your TabControl's SelectedTab (checks the tab's name) or SelectedIndex (checks the tab's position) property. Here's the fixed code:
private void BtnSave_Click(object sender, EventArgs e) { // Get the currently selected tab page from your TabControl // Replace "tabControl1" with the actual name of your TabControl var activeTab = tabControl1.SelectedTab; // Switch based on the tab's Name property (matches the Name you set in the designer) switch (activeTab.Name) { case "Tabp1": // Add the new item to ListView ListViewItem item = listView1.Items.Add(NameTB.Text); item.SubItems.Add(FamilTB.Text); item.SubItems.Add(AgeMTB.Text); item.SubItems.Add(ForceStatusCobx.Text); item.SubItems.Add(ForceTypeCobx.Text); item.SubItems.Add(PhNumMTB.Text); item.SubItems.Add(PirsonaliCodeMTB1.Text); // Clear input fields (fixed a typo: "ForceTypCobx" → "ForceTypeCobx") NameTB.Text = string.Empty; FamilTB.Text = string.Empty; AgeMTB.Text = string.Empty; ForceStatusCobx.Text = string.Empty; ForceTypeCobx.Text = string.Empty; PhNumMTB.Text = string.Empty; PirsonaliCodeMTB1.Text = string.Empty; MessageBox.Show("INFO IS register!", "Successful operation", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); break; case "Tabp2": // Add save logic for your second tab here break; // Add more cases for additional tabs as needed } }
Alternative: Use SelectedIndex (By Tab Position)
If you prefer to switch based on the tab's position in the TabControl (0 for first tab, 1 for second, etc.), you can use SelectedIndex instead:
private void BtnSave_Click(object sender, EventArgs e) { switch (tabControl1.SelectedIndex) { case 0: // This is the first tab (Tabp1) // Same save logic as above break; case 1: // Second tab // Corresponding save code break; } }
Key Notes
- Make sure
tabControl1matches the actual name of your TabControl component in the form designer. - Double-check the
Nameproperty of your TabPages (e.g.,Tabp1) to ensure it matches the string in the case statement. - I fixed a typo in your original code:
ForceTypCobx.Textwas misspelled (missing an 'e' →ForceTypeCobx), which would have caused another compile error.
内容的提问来源于stack exchange,提问作者Amir
相关产品推荐
相关产品推荐

