안녕하세요.
오늘은 C#에서 Datagrid의 특정 Cell을 가져오는 방법에 대해 이야기 해 보겠습니다.
우리는 보통 프로그램 중에 Datagrid 내 특정 Cell의 값이나 속성을 가져와
사용하는 경우가 종종 있습니다.
하지만 Datagrid 내 특정 Cell의 값이나 속성을 컨트롤 하는 것은 생각만큼
간단하지 않은 것도 사실입니다.
그래서 아래와 같이 해당 내용을 정리하였으니 C# 초보자분들에게 도움이
되었으면 합니다.(물론 아래 기술 내용 외 다른 방법들도 많이 있겠습니다만
초보자분들이 직관적으로 활용할 수 있는 방법을 기술했습니다.)
먼저 필요한 3개의 함수를 자신의 프로젝트에 맞게 아래와 같이 정의합니다.
public static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
child = GetVisualChild<T>(v);
if (child != null)
break;
}
return child;
}
public static DataGridCell GetdgCell(this DataGrid grid, DataGridRow row, int column)
{
if (row != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
if (presenter == null)
{
grid.ScrollIntoView(row, grid.Columns[column]);
presenter = GetVisualChild<DataGridCellsPresenter>(row);
}
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
return cell;
}
return null;
}
public static IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (null != row) yield return row;
}
}
그리고 실제 Datagrid의 특정 Cell을 가져와 사용하고자 하는 부분에 아래와 같이 작성합니다.
( 아래 내용 중 CommonStaticMethod 는 위 3개의 함수가 정의된 클래스 입니다.)
foreach (DataGridRow row in CommonStaticMethod.GetDataGridRows(DataGrid명))
{
if (row != null)
{
DataGridCell cell = CommonStaticMethod.GetdgCell( DataGrid명 , row, 15);
//해당 Row의 15번째 컬럼을 가져옵니다.
CheckBox ckb = cell.Content as CheckBox;
if (ckb.IsChecked == false)
{
ckb.IsChecked = true;
//체크가 되지 않은 경우 체크가 되도록 변경이 가능합니다. 즉 Cell 속성값을 변경할 수 있습니다.
}
cell = CommonStaticMethod.GetdgCell( DataGrid명 , row, 16);
//해당 Row의 16번째 컬럼을 가져옵니다.
TextBlock tb = cell.Content as TextBlock;
String _abc = tb.Text;
if (string.IsNullOrEmpty(_abc))
{
continue;
}
......
내용이 도움이 되셨나요?
필요하신 분들에게 꼬옥 도움이 되는 공유가 되었으면 좋겠습니다.
언제나 행복하길 기원하겠습니다.
감사합니다. ^^*
그런데 혹시 가슴이 답답해 명상이나 힐링이 필요하시다면?
아래로 한번 들러 주세요~ ^^
https://youtu.be/oRHsThgQdzk?feature=shared
'C#' 카테고리의 다른 글
c# WPF Datagrid csv 파일로 저장하기 (0) | 2024.07.04 |
---|---|
c# WPF 천 단위 콤마(,) 표시하기 (0) | 2024.07.03 |
C# WPF 전역변수 정의하기 (0) | 2023.05.27 |
C# WPF DataGrid 행 선택 시 컬럼 값 가져오기 (0) | 2023.05.23 |
C# WPF DataGrid Cell에 아이콘 넣는 방법 (0) | 2023.05.18 |
댓글