2016-11-02 4 views
0

基本的には、セルから値を取得できません。列には整数のみが含まれています。Convertは例外を与えます。在庫管理のためにGridViewのセルからint値を取得しますか?

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    foreach (GridViewRow fila in Tabla.Rows) 
    { 
     //int celda = Convert.ToInt32(Tabla.Rows[4].ToString()); //ArgumentOutOfRangeException 
     //var celda = Convert.ToInt32(fila.Cells[4].ToString()); //FormatException 
     //var celda = Convert.ToInt32(fila.Cells[4]); //InvalidCastException 
     if (celda > 10) 
     { 
      //Visual Alert on cell 
     } 
    } 
} 

if声明の中では、それは

は、それを行うことも可能ですか私はちょうど私の時間を無駄にしています(など、株式、低在庫切れの)警告を表示する必要がありますか?

答えて

3

RowDataBoundイベントでは、実際にイベントGridViewRowEventArgsを使用して現在の行を取得する必要があります。このようなことをすることができます。

 if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      if (Convert.toInt32(e.Row.Cells[4].Text) > 10) 
      { 
       //alert 
      } 
     } 
0

e.Row.Cells[i].Textを使用してセルデータを確認すると問題が発生する可能性があります。このセルを<%# string.Format("{0:c}", 35000) %>のようにフォーマットすると、整数を35000に戻すと、€ 35.000,00という文字列にフォーマットされているため、Input string was not in a correct formatエラーが発生します。 DateTimeの値も同じです。

より良い方法は、GridViewRowEventArgsを元の形式に戻して比較することです。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      //if the bound data is a generic list, cast back to an individual listitem 
      Book book = e.Row.DataItem as Book; 
      if (book.id > 3) 
      { 
       //add an attribute to the row 
       e.Row.Attributes.Add("style", "background-color: red"); 
       //or hide the entire row 
       e.Row.Visible = false; 
      } 

      //if the bound data is a datatable or sql source, cast back as datarowview 
      DataRowView row = e.Row.DataItem as DataRowView; 
      if (Convert.ToInt32(row["id"]) > 4) 
      { 
       //add an attribute to a cell in the row 
       e.Row.Cells[1].Attributes.Add("style", "background-color: red"); 
       //or replace the contents of the cell 
       e.Row.Cells[1].Text = "SOLD OUT"; 
      } 
     } 
    } 
関連する問題