How to show text in combobox when no item selected?

前端 未结 16 1269
太阳男子
太阳男子 2020-11-30 06:39

C# & .Net 2.0 question (WinForms)

I have set of items in ComboBox and non of them selected. I would like to show a string on combo \"Pl

相关标签:
16条回答
  • 2020-11-30 06:56

    I realize this is an old thread, but just wanted to let others who might search for an answer to this question know, in the current version of Visual Studio (2015), there is a property called "Placeholder Text" that does what jotbek originally asked about. Use the Properties box, under "Common" properties.

    0 讨论(0)
  • 2020-11-30 06:58

    Credit must be given to IronRazerz in a response to TextBox watermark (CueBanner) which goes away when user types in single line TextBox (not for RichTextBox).

    You will need to declare the following in your class:

    private const int CB_SETCUEBANNER = 0x1703;
    
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    private static extern int SendMessage(IntPtr hWnd, int msg, int wParam, [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]string lParam);
    

    Then you can use it with something like:

    SendMessage(this.comboBox1.Handle, CB_SETCUEBANNER, 0, "Please select an item...");
    

    This is assuming the Combo Box's DropDownStyle is set to DropDownList, as is the original poster's question.

    This should result in something like the following:

    0 讨论(0)
  • 2020-11-30 07:01

    I was hoping to find a solution to this as well. I see that this is an older post, but hoping my approach might simplify this problem for someone else.

    I was using a combobox with a drop down style of DropDownList, but this should work with other styles. In my case I wanted the text to read "Select Source" and I wanted the other options to be "File" and "Folder"

    comboBox1.Items.AddRange(new string[] {"Select Source", "File", "Folder" });
    comboBox1.Text = "Select Source";
    

    You can select the 0 index instead if you like. I then removed the "Select Source" item when the index is changed as it no longer matters if that text is visible.

    comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_IndexChanged);
    
    private void comboBox1_IndexChanged(object sender, EventArgs e)
        {
            comboBox1.Items.Remove("Select Source");
            if (comboBox1.SelectedIndex != -1)
            {
                if (comboBox1.SelectedIndex == 0) // File
                {
                    // Do things
                }
                else if (comboBox1.SelectedIndex == 1) // Folder
                {
                    // Do things
                }
            }
        }
    

    Thanks

    0 讨论(0)
  • 2020-11-30 07:02
        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            if (comboBox1.Text == "")
                comboBox1.Text = "Select one of the answers"; 
        }
    

    should do the trick at startup this line is present, when selected an item on combobox, this items text will appear. when deleling the text this text will appear again

    0 讨论(0)
  • 2020-11-30 07:02

    Here you can find solution created by pavlo_ua: If you have .Net > 2.0 and If you have .Net == 2.0 (search for pavlo_ua answer)

    Cheers, jbk

    edit: So to have clear answer not just link

    You can set Text of combobox when its style is set as DropDown (and it is editable). When you have .Net version < 3.0 there is no IsReadonly property so we need to use win api to set textbox of combobox as readonly:

    private bool m_readOnly = false;
    private const int EM_SETREADONLY = 0x00CF;
    
    internal delegate bool EnumChildWindowsCallBack( IntPtr hwnd, IntPtr lParam );
    
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
    
    [ DllImport( "user32.dll" ) ]
    internal static extern int EnumChildWindows( IntPtr hWndParent, EnumChildWindowsCallBack lpEnumFunc, IntPtr lParam );
    
    
    private bool EnumChildWindowsCallBackFunction(IntPtr hWnd, IntPtr lparam)
    {
          if( hWnd != IntPtr.Zero )
           {
                  IntPtr readonlyValue = ( m_readOnly ) ? new IntPtr( 1 ) : IntPtr.Zero;
                 SendMessage( hWnd, EM_SETREADONLY, readonlyValue, IntPtr.Zero );
                 comboBox1.Invalidate();
                 return true;
           }
           return false;
    }
    
    private void MakeComboBoxReadOnly( bool readOnly )
    {
        m_readOnly = readOnly;
        EnumChildWindowsCallBack callBack = new EnumChildWindowsCallBack(this.EnumChildWindowsCallBackFunction );
        EnumChildWindows( comboBox1.Handle, callBack, IntPtr.Zero );
    }
    
    0 讨论(0)
  • 2020-11-30 07:02

    Unfortunately none of the above worked for me, so instead I added a label on top of the comboxbox that says "Please select". I used the following code to show and hide it:

    1. When I initialise my combobox, if there is no selected value I bring it to the front and set the text:

      PleaseSelectValueLabel.BringToFront();
      PleaseSelectValueLabel.Text = Constants.AssessmentValuePrompt;
      
    2. If there is a value selected I send it to the back:

      PleaseSelectValueLabel.SendToBack();
      
    3. I then use the following events to move the label to the front or back depending on whether the user has selected a value:

      private void PleaseSelectValueLabel_Click(object sender, EventArgs e)
      {
          PleaseSelectValueLabel.SendToBack();
          AssessmentValue.Focus();
      }
      
      private void AssessmentValue_Click(object sender, EventArgs e)
      {
          PleaseSelectValueLabel.SendToBack();
      }
      
      //if the user hasnt selected an item, make the please select label visible again
      private void AssessmentValue_Leave(object sender, EventArgs e)
      {
          if (AssessmentValue.SelectedIndex < 0)
          {
              PleaseSelectValueLabel.BringToFront();
          }
      }
      
    0 讨论(0)
提交回复
热议问题