문제

string percentage = e.Row.Cells[7].Text;

GridView로 역동적 인 작업을 수행하려고 노력하고 있으므로 RowDatabound 이벤트에 코드를 연결했습니다. 나는 템플릿 필드 인 특정 셀에서 값을 얻으려고 노력하고 있습니다. 그러나 위의 코드는 항상 빈 문자열을 반환하는 것 같습니다.

어떤 아이디어?

명확히하기 위해, 여기에 약간의 불쾌한 셀이 있습니다.

<asp:TemplateField HeaderText="# Percentage click throughs">
<ItemTemplate>
    <%# AddPercentClickThroughs((int)Eval("EmailSummary.pLinksClicked"), (int)Eval("NumberOfSends")) %>
</ItemTemplate>
</asp:TemplateField>

관련 메모에서, 줄에서 셀을 선택하는 더 나은 방법이 있는지 아는 사람이 있습니까? 그것은 짜증납니다 cell[1]. 내가 할 수 없었습니다 cell["mycellname"], 셀의 순서를 변경하기로 결정하면 버그가 나타나지 않습니까?

도움이 되었습니까?

해결책

먼저 코드를 랩핑해야합니다 Label 또는 Literal 제어 할 수 있도록 제어하십시오. 일어나고있는 것은 텍스트와 관련된 제어가 없기 때문에 시스템이 추적 할 수있는 방법이 없다는 것입니다. 내용을 ViewState에 추가하는 것은 통제의 책임입니다.

GridView.FindControl ( "ControlName")을 사용해야합니다. 줄에서 제어를 얻기 위해. 거기에서 당신은 그 속성을 포함한 속성을 얻을 수 있습니다 Text.

또한 해당 행의 DataIitem 속성을 얻고 적절한 유형으로 캐스트하여 정보를 직접 추출 할 수 있습니다.

다른 팁

데이터를 데이터 소스에서 직접 가져 오십시오.

DataBinder.Eval(e.Row.DataItem, "ColumnName")

템플릿 필드를 사용하고 문자 그대로 텍스트를 바인딩 할 때 ASP.NET은 실제로 컨트롤을 삽입합니다! DataboundLiteralControl에 넣습니다. 빈 텍스트를 얻는 코드 줄 근처의 디버거를 보면 이것을 볼 수 있습니다.

따라서 컨트롤을 사용하도록 템플릿을 변경하지 않고 정보에 액세스하려면 다음과 같은 캐스트를 수행합니다.

string percentage = ((DataBoundLiteralControl)e.Row.Cells[7].Controls[0]).Text;

그것은 당신에게 당신의 텍스트를 얻을 것입니다!

위의 좋은 제안은 좋은 제안이지만, 문자 그대로 또는 레이블 컨트롤로 래핑하지 않고 그리드보기에서 셀의 텍스트 값을 얻을 수 있습니다. 당신은 어떤 이벤트를 연결 해야하는지 알아야합니다. 이 경우 대신 데이터 라운드 이벤트를 사용하십시오.

protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[0].Text.Contains("sometext"))
        {
            e.Row.Cells[0].Font.Bold = true;
        }
    }
}

디버거를 실행할 때이 방법에 텍스트가 나타납니다.

루프를 사용하여 그리드 뷰에서 셀을 확인하십시오.

for (int i = 0; i < GridView2.Rows.Count; i++)
{
    string vr;
    vr = GridView2.Rows[i].Cells[4].Text; // here you go vr = the value of the cel
    if (vr  == "0") // you can check for anything
    {
        GridView2.Rows[i].Cells[4].Text = "Done";
        // you can format this cell 
    }
}

사용 RowDataBound 인염 셀과 데이터를 바인딩하고 제어 사용을 얻는 기능 (DropdownList와 같은 ASP 제어 이름) GridView.FindControl("Name of Control")

비슷한 질문이 있었지만 약간 다른 접근법을 통해 해결책을 찾았습니다. Chris가 제안한대로 컨트롤을 찾는 대신 먼저 .aspx 페이지에 필드가 지정된 방식을 변경했습니다. a를 사용하는 대신 <asp:TemplateField ...> 태그, 문제의 필드를 사용하도록 변경했습니다. <asp:BoundField ...>. 그런 다음 RowDatabound 이벤트에 도착하면 셀에서 데이터에 직접 액세스 할 수 있습니다.

관련 조각 : 먼저 ASPX 페이지 :

<asp:GridView ID="gvVarianceReport" runat="server" ... >
...Other fields...
    <asp:BoundField DataField="TotalExpected" 
     HeaderText="Total Expected <br />Filtration Events" 
     HtmlEncode="False" ItemStyle-HorizontalAlign="Left" 
     SortExpression="TotalExpected" />
...
</asp:Gridview>

그런 다음 행 변위 이벤트에서 값에 직접 액세스 할 수 있습니다.

protected void gvVarianceReport_Sorting(object sender, GridViewSortEventArgs e)
{
    if (e.Row.Cells[2].Text == "0")
    {
        e.Row.Cells[2].Text = "N/A";
        e.Row.Cells[3].Text = "N/A";
        e.Row.Cells[4].Text = "N/A";
    }
}

누군가 댓글을 달 수 있다면 이것은 작동합니다. 감사합니다. 바운드 필드가 없으면 값이 바인드 후 셀에 있지 않은 이유를 완전히 이해하지 못하지만 컨트롤을 통해 찾아야합니다.

Label lblSecret = ((Label)e.Row.FindControl("lblSecret"));
<asp:TemplateField HeaderText="# Percentage click throughs">
  <ItemTemplate>
    <%# AddPercentClickThroughs(Convert.ToDecimal(DataBinder.Eval(Container.DataItem, "EmailSummary.pLinksClicked")), Convert.ToDecimal(DataBinder.Eval(Container.DataItem, "NumberOfSends")))%>
  </ItemTemplate>
</asp:TemplateField>


public string AddPercentClickThroughs(decimal NumberOfSends, decimal EmailSummary.pLinksClicked)
{
    decimal OccupancyPercentage = 0;
    if (TotalNoOfRooms != 0 && RoomsOccupied != 0)
    {
        OccupancyPercentage = (Convert.ToDecimal(NumberOfSends) / Convert.ToDecimal(EmailSummary.pLinksClicked) * 100);
    }
    return OccupancyPercentage.ToString("F");
}

속성을 설정하면 보이는 ASP : Boundfield to 거짓. 이와 같이

<asp:BoundField DataField="F1" HeaderText="F1" Visible="False"/>

당신은 할 것입니다 ~ 아니다 행을 루프 할 때 셀에서 텍스트를 가져옵니다. 그래서

foreach (GridViewRow row in myGrid.Rows)
{
  userList.Add(row.Cells[0].Text); //this will be empty ""
}

그러나 그리드를 onrowdatabound에 이벤트에 연결하여 표시되지 않은 열을 설정할 수 있습니다.

e.Row.Cells[0].Visible = false //now the cell has Text but it's hidden
protected void gvbind_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';";
        e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
        e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvbind, "Select$" + e.Row.RowIndex);
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top