Rambler's Top100
Главная
Новости
Статьи
Форумы
Книги
Коды
Сообщество
Блоги
О нас
 

Логин

Email:
  Пароль:

Войти
Зарегистрироваться
Забыл пароль

Поиск

 Искать :
 
Вперед

Книги по теме

Искать:
в:
Порядок:

Исходник

Автор:

V©R©N

 
Название:

DataGridComboboxColumn

Дата: 07 October 2002
Описание: Вопрос создания сложных контролов в ячейках стандартного грида часто поднимается на форуме. Надеюсь данный исходник поможет разрешить данную проблему. 
  Разместить ссылку на этот исходник в форуме вы можете вставив в текст сообщения следующую строку: [CODEPOST ID=8]DataGridComboboxColumn[/CODEPOST]
Оценка: Проголосовало 7 посетителей, средняя оценка 3.29
Оценить:
  1 using System;
  2 using System.Windows.Forms;
  3 
  4 namespace DataGridComboboxColumnSample
  5 {
  6 	/// <summary>
  7 	/// Summary description for DataGridComboBox.
  8 	/// </summary>
  9 	public class DataGridComboBox : ComboBox
 10 	{
 11        	private bool isInEditOrNavigateMode = true;
 12         
 13         public DataGridComboBox()
 14 		{
 15 			this.DropDownStyle = ComboBoxStyle.DropDownList;
 16 		}
 17 	}
 18 }
 19 
 20 using System;
 21 using System.Collections;
 22 using System.ComponentModel;
 23 using System.Drawing;
 24 using System.Windows.Forms;
 25 
 26 namespace DataGridComboboxColumnSample {
 27 	/// <summary>
 28 	/// A sample DataGrid ComboBox column
 29 	/// </summary>
 30 	public class DataGridComboBoxColumnStyle : DataGridColumnStyle
 31 	{
 32 
 33 		// UI Constants
 34 		private int              xMargin =           2;
 35 		private int              yMargin =           1;
 36 		private DataGridComboBox combo;
 37 	
 38 		// Used to track editing state
 39 		private string oldValue = null;
 40 		private bool   inEdit   = false;
 41 	
 42 		/// <summary>
 43 		///     Create a new column
 44 		/// </summary>
 45 		public DataGridComboBoxColumnStyle()
 46 		{
 47 			combo = new DataGridComboBox();
 48 			combo.Visible = false;
 49 		}
 50 
 51 
 52 		//----------------------------------------------------------
 53 		//Properties to allow us to set up the datasource for the ComboBox
 54 		//----------------------------------------------------------
 55 
 56 		/// <summary>
 57 		///     The DataSource for values to display in the ComboBox
 58 		/// </summary>
 59 		public object DataSource 
 60 		{ 
 61 			get { return combo.DataSource; }
 62 			set { combo.DataSource = value;}
 63 		}
 64 
 65 		/// <summary>
 66 		///     The property to display for each item in the combobox
 67 		/// </summary>
 68 		public string DisplayMember
 69 		{
 70 			get { return combo.DisplayMember; }
 71 			set { combo.DisplayMember = value; }
 72 		}
 73 
 74 		/// <summary>
 75 		///     The name of the property that we are going to set the value for
 76 		/// </summary>
 77 		public string ValueMember 
 78 		{
 79 			get { return combo.ValueMember; }
 80 			set { combo.ValueMember = value; }
 81 		}
 82 
 83 		//----------------------------------------------------------
 84 		//Methods overridden from DataGridColumnStyle
 85 		//----------------------------------------------------------
 86 
 87 		protected override void Abort(int rowNum)
 88 		{
 89 			RollBack();
 90 			HideComboBox();
 91 			EndEdit();
 92 		}
 93 		protected override bool Commit(CurrencyManager dataSource, int rowNum)
 94 		{ 
 95 			HideComboBox();
 96 
 97 			//If we are not in an edit then simply return
 98 			if (!inEdit)
 99 				return true; 
100 			try
101 			{
102 				object value = combo.SelectedValue;
103 				if (NullText.Equals(value)) 
104 				value = Convert.DBNull;
105 				SetColumnValueAtRow(dataSource, rowNum, value);
106 			}
107             catch (Exception)
108 			{
109 				RollBack();
110                 return false;
111 			}
112             EndEdit();
113             return true;
114 		}
115 
116 		protected override void ConcedeFocus()
117 		{
118         	combo.Visible = false;
119         }
120 
121 
122         protected override void Edit(CurrencyManager source,
123         	int rowNum,
124 			Rectangle bounds,
125             bool readOnly,
126             string instantText,
127             bool cellIsVisible)
128 		{
129             combo.Text = "" ;
130 
131             Rectangle originalBounds = bounds;
132 
133             combo.SelectedValue = GetText(GetColumnValueAtRow(source, rowNum));
134 
135             if (instantText != null) 
136 				combo.SelectedValue = instantText;
137 
138             oldValue = combo.Text;
139 
140             if (cellIsVisible) 
141 			{
142 				bounds.Offset(xMargin, yMargin);
143                	bounds.Width  -= xMargin*2;
144                 bounds.Height -= yMargin;
145                 combo.Bounds = bounds;
146 
147                 combo.Visible = true;
148             }
149             else 
150 			{
151             	combo.Bounds = originalBounds;
152             	combo.Visible = false;
153             }
154 
155             combo.RightToLeft = this.DataGridTableStyle.DataGrid.RightToLeft;
156 
157 			combo.Focus();
158             
159             if (instantText == null)
160             	combo.SelectAll();
161             else 
162 			{
163             	int end = combo.Text.Length;
164             	combo.Select(end, 0);
165             }
166 
167             if (combo.Visible) 
168 				DataGridTableStyle.DataGrid.Invalidate(originalBounds);
169             inEdit = true;
170         }
171 
172 
173 	    protected override int GetMinimumHeight() 
174 		{
175 			//Set the minimum height to the height of the combobox
176             return combo.PreferredHeight + yMargin;
177         }
178 
179        	protected override int GetPreferredHeight(Graphics g, object value)
180 		{
181 			int newLineIndex = 0;
182            	int newLines = 0;
183            	string valueString = this.GetText(value);
184             	
185 			while (newLineIndex != -1 ) 
186 			{
187                	newLineIndex = valueString.IndexOf("\r\n", newLineIndex + 1);
188                	newLines ++;
189            	}
190 
191            	return FontHeight * newLines + yMargin;
192        	}
193 
194        	protected override Size GetPreferredSize(Graphics g, object value) 
195 		{
196            	Size extents = Size.Ceiling(g.MeasureString(GetText(value), this.DataGridTableStyle.DataGrid.Font));
197            	extents.Width += xMargin*2 + DataGridTableGridLineWidth;
198            	extents.Height += yMargin;
199            	return extents;
200        	}
201        
202        	protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) 
203 		{
204            	Paint(g, bounds, source, rowNum, false);
205        	}
206 
207        	protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) 
208 		{
209            	//NOTE: Text to paint should really be driven off 
210            	//      DisplayMember/ValueMember for Combo-box
211            	string text = GetText(GetColumnValueAtRow(source, rowNum));
212            	PaintText(g, bounds, text, alignToRight);
213        	}
214 
215        	protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source,
216 			int rowNum,Brush backBrush, Brush foreBrush, bool alignToRight) 
217 		{
218            	string text = GetText(GetColumnValueAtRow(source, rowNum));
219            	PaintText(g, bounds, text, backBrush, foreBrush, alignToRight);
220        	}
221 
222        	protected override void SetDataGridInColumn(DataGrid value) 
223 		{
224            	base.SetDataGridInColumn(value);
225            	if (combo.Parent != value) 
226 			{
227            		if (combo.Parent != null) 
228            			combo.Parent.Controls.Remove(combo);
229            	}
230            	if (value != null) 
231 				value.Controls.Add(combo);
232        	}
233 
234        	protected override void UpdateUI(CurrencyManager source, int rowNum, string instantText)
235 		{
236            	combo.Text = GetText(GetColumnValueAtRow(source, rowNum));
237 
238 			if (instantText != null) 
239                	combo.Text = instantText;
240         }
241 
242         //----------------------------------------------------------
243         //Helper Methods 
244         //----------------------------------------------------------
245 
246 
247         private int DataGridTableGridLineWidth 
248 		{
249            	get { return this.DataGridTableStyle.GridLineStyle == DataGridLineStyle.Solid ? 1 : 0;}
250         }
251 
252 		private void EndEdit() 
253 		{
254         	inEdit = false;
255         	Invalidate();
256         }
257 
258         private string GetText(object value) 
259 		{
260         	if (value is System.DBNull) 
261            		return NullText;
262         	return(value != null ? value.ToString() : "");
263         }
264 
265         private void HideComboBox() 
266 		{
267 			if (combo.Focused) 
268             	this.DataGridTableStyle.DataGrid.Focus();
269             combo.Visible = false;
270         }
271 
272         private void RollBack() 
273 		{
274 			combo.Text = oldValue;
275         }
276 
277 		private void PaintText(Graphics g, Rectangle bounds, string text, bool alignToRight) 
278 		{
279 			Brush backBrush = new SolidBrush(this.DataGridTableStyle.BackColor);
280 			Brush foreBrush = new SolidBrush(this.DataGridTableStyle.ForeColor);
281 			PaintText(g, bounds, text, backBrush, foreBrush, alignToRight);
282 		}
283 
284         private void PaintText(Graphics g, Rectangle textBounds, string text, Brush backBrush, Brush foreBrush, bool alignToRight) 
285 		{
286        		Rectangle rect = textBounds;
287 
288 			StringFormat format = new StringFormat();
289             if (alignToRight) 
290             	format.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
291 
292 			format.Alignment = this.Alignment == HorizontalAlignment.Left ? StringAlignment.Near : this.Alignment == HorizontalAlignment.Center ? StringAlignment.Center : StringAlignment.Far;
293 
294 			format.FormatFlags |= StringFormatFlags.NoWrap;
295 
296 			g.FillRectangle(backBrush, rect);
297 
298 			// by design, painting  leaves a little padding around the rectangle.
299             // so do not deflate the rectangle.
300             rect.Offset(0,yMargin);
301             rect.Height -= yMargin;
302             g.DrawString(text, this.DataGridTableStyle.DataGrid.Font, foreBrush, rect, format);
303             format.Dispose();
304         }
305 	}
306 }
307 
Вернуться к списку исходников в категории Winforms
 
Наш Киев

Apartments for Rent

Rambler's Top100
Рейтинг@Mail.ru
Идея: Dimon aka Manowar Программирование: Dimon aka Manowar Дизайн: Dan Lebedev
Хостинг от компании Parking.ru
Карта сайта