2011-09-12 3 views
3

나는 TimeReceived가 null의 경우 1. 레드를 표시하는 것을 시도하고, (나)에 따라 2. 호박 수신 시간이 null가 아니고, 시간 읽기가 null (또는) 3 시간 읽기는 조건

null가 아닌 경우 내가 조건에 따라 이미지를 표시 할 수있는 방법, 잘못된 갈거야 곳. 그린이 오류

Input string was not in a correct format. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.FormatException: Input string was not in a correct format. 

Source Error: 


Line 86:   { 
Line 87:    Image img = (Image)e.Row.FindControl("image1"); 
Line 88:    switch (int.Parse(e.Row.Cells[1].Text)) 
Line 89:    { 
Line 90:     case 0: 

에게 던졌습니다. 나는 rowdatabound를 제대로하지 않았다고 생각합니다. 도와주세요.

+1

뭔가 떠나는 것 같습니다. 그리드의 이미지를 보면 Cells [1]의 데이터가 정수가 아닌 datetime 인 것처럼 보입니다. 이것은 구문 분석에 대해 틀린 형식 예외를 던질 것입니다. ID에 맞는 셀 #에 액세스하고 있는지 확인하십시오. –

답변

2

아마도 널 또는 빈 문자열을 int로 구문 분석하려고합니다.

switch (int.Parse(string.IsNullOrEmpty(e.Row.Cells[1].Text)?"0":e.Row.Cells[1].Text)) 

UPDATE :에 int.Parse 줄을 변경을 이제 격자 모양을의 실제 이미지를 붙여 넣은 것을, 나는 당신이 정수로 날짜를 구문 분석하려고하는, 조엘 Etherton 잘 생각합니다. Cell [1] (왼쪽에 보이지 않는 열이 없다고 가정)은 정수가 아닌 Date이므로 int를 파싱합니다. Parse는 파싱 할 수 없기 때문에 예외를 throw합니다. 또한 조건에 따라 MyGrid_RowDataBound 논리가 올바르지 않습니다. 구현 방식을 변경해보십시오.

protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     Image img = (Image)e.Row.FindControl("image1"); 
     //condition for red image; Neither TimeReceived and TimeRead are populated 
     if(string.IsNullOrEmpty(e.Row.Cells[1].Text) && 
      string.IsNullOrEmpty(e.Row.Cells[2].Text)) 
     { 
      img.ImageUrl = "/images/Red.gif"; 
      img.Visible = true; 
     } 
     //condition for amber image; TimeReceived not null and TimeRead is null 
     else if (!string.IsNullOrEmpty(e.Row.Cells[1].Text) && 
       string.IsNullOrEmpty(e.Row.Cells[2].Text)) 
     { 
      img.ImageUrl = "/images/Amber.gif"; 
      img.Visible = true; 
     } 
     //condition for green image; TimeReceived not null and TimeRead not null 
     else if (!string.IsNullOrEmpty(e.Row.Cells[1].Text) && 
       !string.IsNullOrEmpty(e.Row.Cells[2].Text)) 
     { 
      img.ImageUrl = "/images/Green.gif"; 
      img.Visible = true; 
     } 
     else //default case 
     { 
      img.Visible = false; 
     } 
    } 
} 
+0

아, 그래, 고마워, 같은 오류가 발생했습니다 입력 문자열이 올바른 형식이 아닙니다. – Mark

+0

@ 마크 : 내 대답에 대한 업데이트를 확인하십시오. – Icarus

0

나는 이카루스에 동의하지만 int.Parse 대신 int.TryParse를 사용하면 더 좋을 것입니다.

Image img = (Image)e.Row.FindControl("image1"); 
int val = 0; 
int.TryParse(e.Row.Cells[1].Text , out val); 
     switch (int.Parse(e.Row.Cells[1].Text)) 
     { 
      case 0: 
       img.ImageUrl = "/images/Red.gif"; 
       img.Visible = true; 
       break; 
      case 1: 
       img.ImageUrl = "/images/Amber.gif"; 
       img.Visible = true; 
       break; 
      case 2: 
       img.ImageUrl = "/images/Green.gif"; 
       img.Visible = true; 
       break;    
      default: 
       img.Visible = false; 
       break; 
     } 
1

여기에 문제가있는 것을 볼 수 있습니다. 솔직히이 코드는 다소 엉망입니다.

switch(int.Parse(string.IsNullOrEmpty(e.Row.Cells[1].Text)?"0":e.Row.Cells[1].Text)) 

유용한 정보가 너무 많습니다. 첫째, e.Row.Cells [1]은 DateTime을 제공하는 것처럼 보이므로 int.Parse는 여기에서 사용하는 절대 잘못된 것입니다. 당신이 원하는 것에 대한 귀하의 묘사에 기초하여 나는 이것이 어떤 식 으로든 그것을 성취 할 수있는 방법을 보지 못했습니다.

는 여기에 내 찔린입니다 : if 문

Image img = (Image)e.Row.FindControl("image1"); 

DateTime received; 
DateTime read; 

DateTime.TryParse(e.Row.Cells[1].Text, received); // If exception it will produce DateTime.MinValue 
DateTime.TryParse(e.Row.Cells[2].Text, read); 

if (received == DateTime.MinValue) 
{ 
    img.ImageUrl = "/images/Red.gif"; 
} 
else if (read == DateTime.MinValue) 
{ 
    img.ImageUrl = "/images/Amber.gif"; 
} 
else 
{ 
    img.ImageUrl = "/images/Green.gif"; 
} 

img.Visible = true; 

사용 그들이 적절한 때. 당신이하려고하는 것은 날짜를 포함하므로 날짜를 사용하십시오. 표현을 단순화하여 더 쉽게 읽을 수있게하십시오. 모든 것을 한 줄로 처리 할 필요는 없습니다. switch 문에 전달 된 식은 한 번에 너무 많이 수행됩니다. 나는 풀 수 없다는 말은 아니지만 생성 된 오류가 어디에서 오는지에 관해서 많은 회색 영역을 생성합니다.

+0

이 후 이미지 클릭시 onclick 리스너에 액세스하려면 어떻게해야합니까? –

+0

@DeepaMG : ImageUrl의 설정과 마찬가지로 바로 뒤에 클릭 위임을 'img.Click + = SomeClickEventDelegate;'와 함께 추가 할 수 있습니다. –

1

나는이 복잡한 해결책을 이해하는 데 어려움을 겪었으므로 약간의 연구를했고 여기에 내 해결책이 있습니다. 내가

protected boolean ActionPermitted(string action){ 
    return (action=="Delete" || user == "admin"); 
} 

protected string ImageView(DataRow row){ 
    if (row["SomeData"] == DBNull.Value){ 
     return "red.gif"; 
    } else if (row["SomeData"] != DBNull.Value && row["SomeOtherData"] == DBNull.Value){ 
     return "amber.gif"; 
    } else { 
     return "green.gif"; 
    } 
} 

이 있음을 유의하시기 바랍니다 기능을 다음 한 뒤에 나는 내 코드에서이

<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="false" OnRowCommand="RowCommand"> 
    <Columns> 
     <asp:TemplateField HeaderText="Commands"> 
      <ItemTemplate><asp:ImageButton ID="btnDelete" Visible='<%# ActionPermitted("DELETE") %>' runat="server" ImageUrl="images/bin.png" ToolTip="Delete" CommandName="Delete" CommandArgument='<%# Eval("Id")%>' /></ItemTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField HeaderText="ASPImage"> 
      <ItemTemplate><asp:Image runat="server" ID="rowImage" ImageUrl='<%# ImageView(((System.Data.DataRowView) Container.DataItem).Row)%>' /></ItemTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField HeaderText="HTMLImage"> 
      <ItemTemplate><img src='<%# ImageView(((System.Data.DataRowView) Container.DataItem).Row)%>' /></ItemTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField HeaderText="SetVisible"> 
      <ItemTemplate> 
       <img src="green.gif" style='display:<%# Eval("aColumn") == "Value1"? "inline":"none" %>' /> 
       <img src="red.gif" style='display:<%# Eval("aColumn") == "Value2"? "none":"inline" %>' /> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 

처럼 내 그리드 코드를 변경

누군가 도움을 기대하고 여기두고 실제로 4 가지 솔루션.

  • 에 따라 결과를 뒤에 코드를 반환하는 현재의 DataRow를 전달하려면 함수 뒤에 코드 (대신 큰 따옴표의 단일 인용 부호에 유의)에서 반환 된 값을 기반으로 ASP를 버튼의 가시성을 변경하려면 HTML 태그의 속성을 변경하려면
  • 는 (모든 태그를 할 수 있습니다)/숨기기 및 HTML 이미지를 표시하려면

마지막 TemplateField가이다 (열로 뒤에 코드에서 생성 된 데이터를 삽입 할 수 있습니다) 질문 nswer.