下拉框有DropDownStyle這一屬性,把DropDownStyle類型選為DropDownList,則下拉框只能選擇不能輸入了。但是這時的下拉框是沒有默認值的,即使在Text屬性中輸入默認值,也不起作用。就要在(某某某.Designer.cs)文件中修改。
這是沒有修改的:
this.NameTemplateBox.Cursor = System.Windows.Forms.Cursors.Default;
this.NameTemplateBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.NameTemplateBox.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.NameTemplateBox.FormattingEnabled = true;
this.NameTemplateBox.Items.AddRange(new object[] {
"-- choose the template --",
"First",
"First,Last",
"First,Middle,Last"});
this.NameTemplateBox.Location = new System.Drawing.Point(138, 124);
this.NameTemplateBox.Name = "NameTemplateBox";
this.NameTemplateBox.Size = new System.Drawing.Size(150, 23);
this.NameTemplateBox.TabIndex = 15;
加粗的那行代碼是下拉框只能選擇不能輸入的設置。
要在那行代碼之前加一句默認值的設置。修改如下:
this.NameTemplateBox.Cursor = System.Windows.Forms.Cursors.Default;
this.NameTemplateBox.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.NameTemplateBox.FormattingEnabled = true;
this.NameTemplateBox.Items.AddRange(new object[] {
"-- choose the template --",
"First",
"First,Last",
"First,Middle,Last"});
this.NameTemplateBox.Text = this.NameTemplateBox.Items[0].ToString();
this.NameTemplateBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.NameTemplateBox.Location = new System.Drawing.Point(138, 124);
this.NameTemplateBox.Name = "NameTemplateBox";
this.NameTemplateBox.Size = new System.Drawing.Size(150, 23);
this.NameTemplateBox.TabIndex = 15;
如果第一行加粗的改為
this.NameTemplateBox.Text =“默認值”;
則和在屬性中直接輸入默認值一樣,會被自動刪除掉。
注意:第一行加粗的語句要寫在
this.NameTemplateBox.Items.AddRange(new object[] {
"-- choose the template --",
"First",
"First,Last",
"First,Middle,Last"});
語句的后面。上面的語句可以在Items的屬性中設置。
以上都寫好后,就會實現效果,但是效果在一些組件有改變(即使不和下拉框有關聯的),整個文件會重構,里面修改過的語句就會還原到,等於什么也沒有改。換句話說,就是每次組件的修改,就要把上面的動作在做一遍。。。。。。
我的方法是把默認值的賦值全部寫在另一個自己寫的方法里面,然后在初始化組建之后,調用這個方法。