행에 바인딩된 개체에 액세스(BindingList 사용권장)
BindList은 목록 데이터 원본이 편집을 지원하도록 하기 위해 데이터 바인딩 인프라에 필요한 최소 인터페이스구현되어져 있따!
http://msdn.microsoft.com/ko-kr/library/ms132679.aspx
void invoiceButton_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in this.dataGridView1.SelectedRows) { Customer cust = row.DataBoundItem as Customer; if (cust != null) { cust.SendInvoice(); } } }
표시를 위해 셀 내용의 서식을 지정해야 하는 경우?
CellFormatting 이벤트
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { // If the column is the Artist column, check the // value. if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Artist") { if (e.Value != null) { // Check for the string "pink" in the cell. string stringValue = (string)e.Value; stringValue = stringValue.ToLower(); if ((stringValue.IndexOf("pink") > -1)) { e.CellStyle.BackColor = Color.Pink; } } } else if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Release Date") { ShortFormDateFormat(e); } } //Even though the date internaly stores the year as YYYY, using formatting, the //UI can have the format in YY. private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting) { if (formatting.Value != null) { try { System.Text.StringBuilder dateString = new System.Text.StringBuilder(); DateTime theDate = DateTime.Parse(formatting.Value.ToString()); dateString.Append(theDate.Month); dateString.Append("/"); dateString.Append(theDate.Day); dateString.Append("/"); dateString.Append(theDate.Year.ToString().Substring(2)); formatting.Value = dateString.ToString(); formatting.FormattingApplied = true; } catch (FormatException) { // Set to false in case there are other handlers interested trying to // format this DataGridViewCellFormattingEventArgs instance. formatting.FormattingApplied = false; } } }
http://msdn.microsoft.com/ko-kr/library/ms404353.aspx
Windows Forms DataGridViewComboBoxCell
드롭다운 목록의 개체 액세스
만들기
public Form1() { InitializeComponent(); employees.Add(new Employee("Harry")); employees.Add(new Employee("Sally")); employees.Add(new Employee("Roy")); employees.Add(new Employee("Pris")); DataSet1TableAdapters.SchoolTableAdapter adapter = new TestWindowsFormsApplication.DataSet1TableAdapters.SchoolTableAdapter(); DataSet1.SchoolDataTable dt = adapter.GetData(); this.bindingSource1.DataSource = employees; ////ComboBoxColumn 생성 DataGridViewComboBoxColumn assignedtocolumn = new DataGridViewComboBoxColumn(); assignedtocolumn.Name = "Column1"; assignedtocolumn.DisplayMember = "name"; assignedtocolumn.ValueMember = "self"; assignedtocolumn.DataSource = employees; this.dataGridView1.AutoGenerateColumns = false; dataGridView1.Columns.Add(assignedtocolumn); this.dataGridView1.DataSource = dt; }
클릭했을때 값 가져오기
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { // Retrieve the Employee object from the "Assigned To" cell. Employee assignedTo = dataGridView1.Rows[e.RowIndex].Cells["Column1"].Value as Employee; // Retrieve the task ID. string taskID = dataGridView1[0, e.RowIndex].Value.ToString(); // Request status through the Employee object if present. if (assignedTo != null) { assignedTo.RequestStatus(taskID); } else { MessageBox.Show(String.Format( "Task {0} is unassigned.", taskID), "Status Request"); } }
선택된 드롭다운리스트 개체가져오기
CellClick 이벤트등록
// Add a CellClick handler to handle clicks in the button column. dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
이벤트가 일어났을때 처리
// Retrieve the Employee object from the "Assigned To" cell. Employee assignedTo = dataGridView1.Rows[e.RowIndex].Cells["Assigned To"].Value as Employee;
DataGridViewLinkCell 등등 기본컨트롤 값 가져오기
private void dgvDocWork_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { DataGridViewLinkCell linkCell =dgvDocWork.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewLinkCell; } private void dgvDocWork_CellContentClick(object sender, DataGridViewCellEventArgs e) { }
컨트롤에서 새 행에 기본값 지정
(새행추가시 미리 입력값을 넣어주기)
private void dataGridView1_DefaultValuesNeeded(object sender, System.Windows.Forms.DataGridViewRowEventArgs e) { e.Row.Cells["Region"].Value = "WA"; e.Row.Cells["City"].Value = "Redmond"; e.Row.Cells["PostalCode"].Value = "98052-6399"; e.Row.Cells["Region"].Value = "NA"; e.Row.Cells["Country"].Value = "USA"; e.Row.Cells["CustomerID"].Value = NewCustomerId(); }
유효성검사
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { // Validate the CompanyName entry by disallowing empty strings. if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName") { if (String.IsNullOrEmpty(e.FormattedValue.ToString())) { dataGridView1.Rows[e.RowIndex].ErrorText = "Company Name must not be empty"; e.Cancel = true; } } } void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { // Clear the row error in case the user presses ESC. dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty; }
데이터 입력 중에 발생하는 오류 처리
DataGridView의 DataError 이벤트를 처리
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e) { // If the data source raises an exception when a cell value is // commited, display an error message. if (e.Exception != null && e.Context == DataGridViewDataErrorContexts.Commit) { MessageBox.Show("CustomerID value must be unique."); } }
'C#.NET' 카테고리의 다른 글
openFileDialog로 텍스트파일 선택하기 (0) | 2010.03.06 |
---|---|
[MSDN]DataGridView 셀에서 컨트롤 호스팅 (0) | 2010.03.03 |
[Interface]인터페이스가 구현되어져 있는지 확인해보기 (0) | 2010.03.03 |
[ErrorProvider]폼 유효성에 대한 오류 아이콘 표시 (0) | 2010.03.03 |
초간단 숫자 앞에 0 채우기 (0) | 2010.02.25 |
[.Resx 리소스 , Resources]리소스 액세스 (3) | 2010.02.10 |
[Process]외부프로그램 실행 / 익스플로어실행 (0) | 2010.02.08 |
초간단 Custom Controls 만들기 (0) | 2010.02.05 |
초간단한 Login Form 만들기 (0) | 2010.02.04 |
[Form Loading]폼로딩 보여주기 (0) | 2010.02.03 |