asp.net 의 GridView에서 인덱스가 아닌 열 이름으로 셀 값을 가져오는 방법
나는 먹고 있습니다.gridviewasp.net 에서 셀 인덱스가 아닌 열 이름의 셀 값을 원합니다.
셀 열 이름으로 셀 값을 검색하면 어떻게 가능합니까?
GridView열 이름으로 작동하지 않습니다. 바로 그것입니다.datasource그런 것들을 알 수 있는 재산.
여전히 열 이름이 지정된 인덱스를 알아야 하는 경우 도우미 메소드를 만들어 다음과 같이 수행할 수 있습니다.gridview헤더에는 일반적으로 이 정보가 포함되어 있습니다.
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
break;
columnIndex++; // keep adding 1 while we don't have the correct name
}
return columnIndex;
}
위의 코드는 a를 사용한다는 것을 기억하세요.BoundField그런 다음 다음과 같이 사용합니다.
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "myDataField");
string columnValue = e.Row.Cells[index].Text;
}
}
저는 당신이 그것을 사용할 것을 강력히 제안하고 싶습니다.TemplateField자신만의 컨트롤을 사용하려면 다음과 같은 컨트롤을 더 쉽게 잡을 수 있습니다.
<asp:GridView ID="gv" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
그런 다음 사용합니다.
string columnValue = ((Label)e.Row.FindControl("lblName")).Text;
시간이 오래 걸리지만 이 비교적 작은 코드 조각은 읽고 얻기가 쉬워 보입니다.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int index;
string cellContent;
foreach (TableCell tc in ((GridView)sender).HeaderRow.Cells)
{
if( tc.Text.Equals("yourColumnName") )
{
index = ((GridView)sender).HeaderRow.Cells.GetCellIndex(tc);
cellContent = ((GridView)sender).SelectedRow.Cells[index].Text;
break;
}
}
}
DataRowView를 사용하여 열 인덱스를 가져올 수 있습니다.
void OnRequestsGridRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var data = e.Row.DataItem as DataRowView;
// replace request name with a link
if (data.DataView.Table.Columns["Request Name"] != null)
{
// get the request name
string title = data["Request Name"].ToString();
// get the column index
int idx = data.Row.Table.Columns["Request Name"].Ordinal;
// ...
e.Row.Cells[idx].Controls.Clear();
e.Row.Cells[idx].Controls.Add(link);
}
}
}
람다 애호가용
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var boundFields = e.Row.Cells.Cast<DataControlFieldCell>()
.Select(cell => cell.ContainingField).Cast<BoundField>().ToList();
int idx = boundFields.IndexOf(
boundFields.FirstOrDefault(f => f.DataField == "ColName"));
e.Row.Cells[idx].Text = modification;
}
}
코드 프로젝트에서 발견된 내용을 기반으로 합니다.
그리드의 데이터 원본을 기준으로 데이터 테이블을 선언한 후에는 열 집합에서 열 이름별로 열 인덱스를 찾습니다.이때 필요에 따라 색인을 사용하여 셀에서 정보를 가져오거나 셀 형식을 지정합니다.
protected void gridMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (DataTable)((GridView)sender).DataSource;
int colIndex = dt.Columns["MyColumnName"].Ordinal;
e.Row.Cells[colIndex].BackColor = Color.FromName("#ffeb9c");
}
}
헤더 행 셀이 작동하지 않을 수 있습니다.그러면 인덱스 열만 반환됩니다.그것은 많은 다양한 방법으로 도움이 될 것입니다.저는 이것이 그가 요구하는 답이 아니라는 것을 알고 있습니다.하지만 이것은 많은 사람들에게 도움이 될 것입니다.
public static int GetColumnIndexByHeaderText(GridView gridView, string columnName)
{
for (int i = 0; i < gridView.Columns.Count ; i++)
{
if (gridView.Columns[i].HeaderText.ToUpper() == columnName.ToUpper() )
{
return i;
}
}
return -1;
}
알렉산더의 대답에 색인 열이 있는 작은 버그:"찾을 수 없음" 열을 처리해야 합니다.
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
int foundIndex=-1;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
{
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
{
foundIndex=columnIndex;
break;
}
}
columnIndex++; // keep adding 1 while we don't have the correct name
}
return foundIndex;
}
그리고.
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "myDataField");
if( index>0)
{
string columnValue = e.Row.Cells[index].Text;
}
}
}
코드 한 줄로 처리할 수 있습니다.아무것도 반복하거나 다른 메소드를 호출할 필요가 없습니다.
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string cellValue = e.Row.Cells[e.Row.Cells.GetCellIndex(e.Row.Cells.Cast<DataControlFieldCell>().FirstOrDefault(cell => cell.ContainingField.HeaderText == "columnName"))].Text;
}
}
//get the value of a gridview
public string getUpdatingGridviewValue(GridView gridviewEntry, string fieldEntry)
{//start getGridviewValue
//scan gridview for cell value
string result = Convert.ToString(functionsOther.getCurrentTime());
for(int i = 0; i < gridviewEntry.HeaderRow.Cells.Count; i++)
{//start i for
if(gridviewEntry.HeaderRow.Cells[i].Text == fieldEntry)
{//start check field match
result = gridviewEntry.Rows[rowUpdateIndex].Cells[i].Text;
break;
}//end check field match
}//end i for
//return
return result;
}//end getGridviewValue
제목이 그렇게 쉽진 않더라도 데이터 필드 이름을 사용하는 것이 가능해서 문제가 해결되었습니다.ASP용.NET & VB:
예: 문자열의 경우:
Dim 인코딩 = e.Row.DataItem("인코딩")입니다.ToString().자르기()
예: 정수의 경우:
Dim Msg 부품 = 변환.Int32(e)로.Row.DataItem("계산된 메시지 부품").문자열로()
protected void CheckedRecords(object sender, EventArgs e)
{
string email = string.Empty;
foreach (GridViewRow gridrows in GridView1.Rows)
{
CheckBox chkbox = (CheckBox)gridrows.FindControl("ChkRecords");
if (chkbox != null & chkbox.Checked)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in gridrows.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals("UserEmail"))
break;
columnIndex++;
}
email += gridrows.Cells[columnIndex].Text + ',';
}
}
Label1.Text = "email:" + email;
}
protected void gvResults_PreRender(object sender, EventArgs e)
{
var gridView = (GridView)sender;
gridView.GetColumnByName("YourDataBoundDataField").Visible = true;
}
확장:
public static DataControlField GetColumnByName(this GridView gridView, string columnName)
{
int columnIndex = -1;
for (int i = 0; i < gridView.Columns.Count; i++)
{
if (gridView.Columns[i].HeaderText.Trim().Equals(columnName, StringComparison.OrdinalIgnoreCase))
{
columnIndex = i;
break;
}
}
if (columnIndex == -1)
{
throw new ArgumentOutOfRangeException("GridViewRow does not have the column with name: " + columnName);
}
return gridView.Columns[columnIndex];
}
그리드 보기 셀에 액세스할 수 있는 셀 이름(ugh)이 없기 때문에 이 작업이 어렵습니다.
이 핸디캡을 해결하기 위해 확장 방법을 만들 수 있습니다(내 것은 VB에 있습니다).NET, 하지만 @дитийрh는 C#에서 비슷한 솔루션을 가지고 있는 것 같습니다.)
이 문제를 해결하려면 그리드 보기 셀의 헤더 텍스트 값이 셀 이름과 동일한지 확인하고 해당 헤더 텍스트 이름을 통해 값을 가져옵니다.
다음은 VB의 문자열과 정수에 필요한 확장 방법입니다.내가 만든 NET 코드 스니펫
Public Shared Function GetStringByCellName(pGridViewRow As GridViewRow, pCellName As String) As String
For Each myCell As DataControlFieldCell In pGridViewRow.Cells
If myCell.ContainingField.ToString() = pCellName Then
Return myCell.Text
End If
Next
Return Nothing
End Function
그리고 정수가 구문 분석/캐스트인 경우의 차이.
Public Shared Function GetIntegerByCellName(pGridViewRow As GridViewRow, pCellName As String) As Integer
For Each myCell As DataControlFieldCell In pGridViewRow.Cells
If myCell.ContainingField.ToString() = pCellName Then
Return Integer.Parse(myCell.Text)
End If
Next
Return Nothing
End Function
그리고 함수를 호출하는 것은 클래스에 있다면 이렇게 보일 것입니다.
Dim columnNamesStringValue As String = ExtensionMethodsClassName.GetStringByCellName(pGridViewRow, "stringOfColumnName")
Dim columnNamesIntegerValue As Integer = ExtensionMethodsClassName.GetIntegerByCellName(pGridViewRow, "stringOfColumnName")
당신이 항상 가치를 얻지는 않을 수도 있고, 대신에 얻을 수도 있다는 것을 명심하세요.Nothing
데이터베이스에 값을 입력하기 전에 값이 아무것도 아님을 확인합니다.그러나 데이터베이스에 삽입하려면 다음을 반환하는 것이 좋습니다.System.DBNull가 제공한 ( 또는 내가제한다확을도공대없는신장것무서아서에드메른. (NULL오삽확지마입하십인고시하)▁()Nothing~하듯이DBNull한 유형의 'S' 다양한유의형유▁'NULL'NOTHINGS Equal
If (columnNamesStringValue IsNot Nothing)
언급URL : https://stackoverflow.com/questions/9715983/how-to-get-the-cell-value-by-column-name-not-by-index-in-gridview-in-asp-net
'programing' 카테고리의 다른 글
| jQuery를 사용하여 드롭다운의 선택한 인덱스 설정 (0) | 2023.08.04 |
|---|---|
| 이동식 SD 카드의 위치 찾기 (0) | 2023.08.04 |
| 오류 코드: 1215.외부 키 제약 조건(외부 키)을 추가할 수 없습니다. (0) | 2023.07.30 |
| 변수가 있지만 "INTO"가 없는 단순 "SELECT" (0) | 2023.07.30 |
| 파이썬에서 두 개의 목록을 사전으로 결합하려면 어떻게 해야 합니까? (0) | 2023.07.30 |