2011-08-29 46 views
1

我有這個代碼,允許用戶上傳csv文件,並且內容將顯示在GridView中,問題是,如果任何行/列爲空,我需要顯示一條錯誤消息,任何人都可以幫助我這個?我不確定使用asp.net c#因爲我是新來的。這是我的代碼:如何檢查和顯示GridView中的空列或行?

protected void btnUpload_Click(object sender, EventArgs e) 
    { 
     string strFileNameOnServer = fileUpload.PostedFile.FileName; 
     string fileExt = 
     System.IO.Path.GetExtension(fileUpload.FileName); 

     if (fileUpload.PostedFile != null && fileExt == ".csv") 
     { 

      try 
      { 

       //fileUpload.PostedFile.SaveAs(ConfigurationManager.AppSettings + appDataPath + "\\" + strFileNameOnServer); 
       fileUpload.PostedFile.SaveAs(Server.MapPath("~/Uploaded")); 
       //string appPath = HttpContext.Current.Request.ApplicationPath; 
       // string physicalPath = HttpContext.Current.Request.MapPath("~/MajorProject"); 
       Label1.Text = "File name: " + 
         fileUpload.PostedFile.FileName + "<br>" + 
         fileUpload.PostedFile.ContentLength + " kb<br>" + 
         "Content type: " + 
         fileUpload.PostedFile.ContentType; 
      } 
      catch (Exception ex) 
      { 
       Label1.Text = "Error saving <b>" + strFileNameOnServer + "</b><br>. " + ex.Message; 
      } 
      BtnImport1.Visible = true; 
      Cancel.Visible = true; 
      fileUpload.Visible = false; 
      btnUpload.Visible = false; 
     } 
     else 
     { 

      Label1.Text = "Error - a file name must be specified/only csv files are allowed"; 
      return; 

     } 


     var data = File.ReadAllLines(Server.MapPath("~/Uploaded")) 
      .Select(line => line.Split(','))  
      .Select(columns => new {GuestName = columns[0], Guest_ID = columns[1], IC_Number = columns[2]}); 
     myGridView.DataSource = data; 
     myGridView.DataBind(); 











    } 

請幫忙!

回答

1

創建方法叫做值或錯誤消息,並通過列[索引]到

.Select(columns => new {GuestName = ValueOrErrorMessage(columns[0]), Guest_ID = ValueOrErrorMessage(columns[1]), IC_Number = ValueOrErrorMessage(columns[2])}); 
     ... 

private string ValueOrErrorMessage(string input){ 
    if(!string.IsNullOrEmpty(input)) 
     return input; 
    } 
    return "no value" 
} 
+0

謝謝!但是我應該在哪裏放置私人字符串ValuOrErrorMessage方法?對不起 – Mark20

+0

只是把它放在btnUpload_Click方法 – kmcc049

+0

那樣做的,但現在它在GuestName = ErrorMessage(列[0])顯示錯誤,錯誤是不能應用與索引[],這個錯誤是什麼? – Mark20