2016-02-05 123 views
-2

根据DGV的使用方式,我无法使用数据绑定。我会发布一切正在完成的事情,几乎是我试图做的事情。问题是,当我尝试点击SAVE时,该方法就好像不知道这个“dataGridView1”字符是谁,就好像它超出了范围,但它没有超出范围。C#--DataGridView - 无法获取ColumnCount,无法获取单元格值

private void RefreshDGV1(){ 
     dataGridView1.DataSource = null; 
     dataGridView1.Columns.Clear(); 
     dataGridView1.Rows.Clear(); 
     string query = (@" 
SELECT HLD_ID  AS 'HLD_ID'    , 
    HoldName AS 'Hold Name'   , 
    BeginDate AS 'Begin Date'   , 
    FileNumber AS 'File Number'  , 
    Operation AS 'Operation'   , 
    Brand  AS 'Brand'    , 
    PAddress AS 'Property Address' , 
    Found  AS 'Found'    , 
    Match  AS 'Address Match'  , 
    Secured  AS 'File Secured'  , 
    Relocated AS 'File Relocated'  , 
    Comment  AS 'Comment' 
FROM Records  
"); 
     //dataGridView1.DataSource  = bindingSource1; 
     //dataGridView1.ColumnCount  = 11; 

     //dataGridView1.Columns[0].Name = "Hold Name"; 
     DataGridViewTextBoxColumn HoldName = new DataGridViewTextBoxColumn(); 
     HoldName.HeaderText    = "Hold Name"; 
     HoldName.Name      = "Hold Name"; 
     HoldName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
     dataGridView1.Columns.Add(HoldName); 

     //dataGridView1.Columns[1].Name  = "Begin Date"; 
     DataGridViewTextBoxColumn BeginDate = new DataGridViewTextBoxColumn(); 
     BeginDate.HeaderText    = "Begin Date"; 
     BeginDate.Name      = "Begin Date"; 
     BeginDate.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
     dataGridView1.Columns.Add(BeginDate); 

     //dataGridView1.Columns[2].Name  = "File Number"; 
     DataGridViewTextBoxColumn FileNumber = new DataGridViewTextBoxColumn(); 
     FileNumber.HeaderText    = "File Number"; 
     FileNumber.Name      = "File Number"; 
     FileNumber.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
     dataGridView1.Columns.Add(FileNumber); 

     //dataGridView1.Columns[3].Name  = "Operation"; 
     DataGridViewTextBoxColumn Operation = new DataGridViewTextBoxColumn(); 
     Operation.HeaderText    = "Operation"; 
     Operation.Name      = "Operation"; 
     Operation.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
     dataGridView1.Columns.Add(Operation); 

     //dataGridView1.Columns[4].Name = "Brand"; 
     DataGridViewTextBoxColumn Brand = new DataGridViewTextBoxColumn(); 
     Brand.HeaderText    = "Brand"; 
     Brand.Name      = "Brand"; 
     Brand.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
     dataGridView1.Columns.Add(Brand); 

     //dataGridView1.Columns[5].Name   = "Property Address"; 
     DataGridViewTextBoxColumn PropertyAddress = new DataGridViewTextBoxColumn(); 
     PropertyAddress.HeaderText    = "Property Address"; 
     PropertyAddress.Name      = "PropertyAddress"; 
     PropertyAddress.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
     dataGridView1.Columns.Add(PropertyAddress); 

     //dataGridView1.Columns[6].Name = "Found"; 
     DataGridViewComboBoxColumn Found = new DataGridViewComboBoxColumn(); 
     Found.HeaderText     = "Found"; 
     Found.Name      = "Found"; 
     Found.Items.Add(""); 
     Found.Items.Add("Found"); 
     Found.Items.Add("Not Found"); 
     Found.Items.Add("In Progress"); 
     Found.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
     dataGridView1.Columns.Add(Found); 

     //dataGridView1.Columns[7].Name   = "Address Match"; 
     DataGridViewComboBoxColumn AddressMatch = new DataGridViewComboBoxColumn(); 
     AddressMatch.HeaderText     = "Address Match"; 
     AddressMatch.Name      = "Address Match"; 
     AddressMatch.Items.Add(""); 
     AddressMatch.Items.Add("Yes"); 
     AddressMatch.Items.Add("No"); 
     AddressMatch.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
     dataGridView1.Columns.Add(AddressMatch); 

     //dataGridView1.Columns[8].Name  = "File Secured"; 
     DataGridViewCheckBoxColumn FileSecured = new DataGridViewCheckBoxColumn(); 
     FileSecured.HeaderText     = "File Secured"; 
     FileSecured.Name      = "File Secured"; 
     FileSecured.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
     dataGridView1.Columns.Add(FileSecured); 

     //dataGridView1.Columns[9].Name   = "File Relocated"; 
     DataGridViewTextBoxColumn FileRelocated = new DataGridViewTextBoxColumn(); 
     FileRelocated.HeaderText    = "File Relocated"; 
     FileRelocated.Name      = "File Relocated"; 
     FileRelocated.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
     dataGridView1.Columns.Add(FileRelocated); 

     //dataGridView1.Columns[10].Name = "Comment"; 
     DataGridViewTextBoxColumn Comment = new DataGridViewTextBoxColumn(); 
     Comment.HeaderText    = "Comment"; 
     Comment.Name      = "Comment"; 
     Comment.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
     Comment.Width = (dataGridView1.Width/11); 
     dataGridView1.Columns.Add(Comment); 

     //dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; 

     //other stuff 
     //dataGridView1.Columns[(dataGridView1.ColumnCount-1)].AutoSizeMode    = DataGridViewAutoSizeColumnMode.DisplayedCells; 
     dataGridView1.Columns[(dataGridView1.ColumnCount-1)].DefaultCellStyle.WrapMode = DataGridViewTriState.True; 
     dataGridView1.CellValueChanged += handler_dataGridView1_CellValueChanged; 
     ReadSQL(query, dataGridView1); 
    } 
private void ReadSQL(string query, DataGridView grid){ 
     try{ 
      string connectionString = "Server=SERVERNAME;Database=DATABASENAME;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD"; 
      dataAdapter = new SqlDataAdapter(query, connectionString); 
      SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); 
      DataTable table = new DataTable(); 
      table.Locale = System.Globalization.CultureInfo.InvariantCulture; 
      dataAdapter.Fill(table); 
      for(int i = 0 ; i < table.Rows.Count; i++){ 
       int n = grid.Rows.Add(); 
       grid.ColumnCount = 11; 
       InitializeComponent(); 

       //Add to ID array (list) 
       RecordIDs.Add(table.Rows[i].ItemArray[0].ToString()); 

       grid.Rows[n].Cells[0].Value = table.Rows[i].ItemArray[1].ToString(); 
       grid.Rows[n].Cells[1].Value = table.Rows[i].ItemArray[2].ToString(); 
       grid.Rows[n].Cells[2].Value = table.Rows[i].ItemArray[3].ToString(); 
       grid.Rows[n].Cells[3].Value = table.Rows[i].ItemArray[4].ToString(); 
       grid.Rows[n].Cells[4].Value = table.Rows[i].ItemArray[5].ToString(); 
       grid.Rows[n].Cells[5].Value = table.Rows[i].ItemArray[6].ToString(); 

       string selection1       = table.Rows[i].ItemArray[7].ToString(); 
       switch(selection1){ 
        case "Found"  : try{grid.Rows[n].Cells[6].Value = (grid.Rows[i].Cells[6] as DataGridViewComboBoxCell).Items[1];}catch{}; break; 
        case "Not Found" : try{grid.Rows[n].Cells[6].Value = (grid.Rows[i].Cells[6] as DataGridViewComboBoxCell).Items[2];}catch{}; break; 
        case "In Progress" : try{grid.Rows[n].Cells[6].Value = (grid.Rows[i].Cells[6] as DataGridViewComboBoxCell).Items[3];}catch{}; break; 
        default   : try{grid.Rows[n].Cells[6].Value = (grid.Rows[i].Cells[6] as DataGridViewComboBoxCell).Items[0];}catch{}; break; 
       } 

       string selection2 = table.Rows[i].ItemArray[8].ToString(); 
       switch(selection2){ 
        case "Yes" : try{grid.Rows[n].Cells[7].Value = (grid.Rows[i].Cells[7] as DataGridViewComboBoxCell).Items[1];}catch{}; break; 
        case "No" : try{grid.Rows[n].Cells[7].Value = (grid.Rows[i].Cells[7] as DataGridViewComboBoxCell).Items[2];}catch{}; break; 
        default : try{grid.Rows[n].Cells[7].Value = (grid.Rows[i].Cells[7] as DataGridViewComboBoxCell).Items[0];}catch{}; break; 
       } 

       try{grid.Rows[n].Cells[8].Value = table.Rows[i].ItemArray[9].ToString();}catch{} 
       try{grid.Rows[n].Cells[9].Value = table.Rows[i].ItemArray[10].ToString();}catch{} 
       try{grid.Rows[n].Cells[10].Value = table.Rows[i].ItemArray[11].ToString();}catch{} 
      } 

      LoadDGV1ToolTips(); 

      grid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); 
      grid.RowHeadersVisible      = false; 
      grid.EnableHeadersVisualStyles    = false; 
      grid.ColumnHeadersDefaultCellStyle.BackColor = Color.DimGray; 
      grid.ColumnHeadersDefaultCellStyle.ForeColor = Color.White; 
      grid.GridColor        = Color.RoyalBlue; 

      for(int i = 0 ; i < grid.Columns.Count; i++){ 
       grid.Columns[i].Width = (grid.Size.Width/grid.Columns.Count) - 1; 
      } 

     }catch(SqlException ex){ 
      MessageBox.Show("SQL ERROR: " + ex.ToString()); 
      MessageBox.Show(query); 
     } 
    } 

private void button4_Click(object sender, EventArgs e){ //SAVE 
     string name  = ""; 
     string date  = ""; 
     string file  = ""; 
     string operation = ""; 
     string brand  = ""; 
     string address = ""; 
     string found  = ""; 
     string match  = ""; 
     string secured = ""; 
     string relocated = ""; 
     string comment = ""; 
     Console.WriteLine("Column Count:  " + this.dataGridView1.ColumnCount); 
     for (int i = 0; i < this.dataGridView1.ColumnCount; i++){ 
      switch(i){ 
       //put some handlers in here for null values, try/catch? 
       case 0: try{name  = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; 
       case 1: try{date  = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; 
       case 2: try{file  = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; 
       case 3: try{operation = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; 
       case 4: try{brand  = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; 
       case 5: try{address = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; 
       case 6: try{found  = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; 
       case 7: try{match  = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; 
       case 8: try{secured = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; 
       case 9: try{relocated = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; 
       case 10: try{comment = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; 
       default: break; //Do Nothing. 
      } 
     } 
     if(secured != "True"){secured = "False";} 
     string query = (@" 
UPDATE Records 
SET HoldName = '" + name + "', BeginDate = '" + date + "', FileNumber = '" + file + "', Operation = '" + operation + "', Brand = '" + brand + "', PAddress = '" + address + "', Found = '" + found + "', Match = '" + match + "', Secured = '" + secured + "', Relocated = '" + relocated + "', Comment = '" + comment + "'" + 
"WHERE HLD_ID = '" + HLD_ID + "'"); 
     //WriteSQL(query); 
     Console.WriteLine("Query: " + query); 
     RefreshDGV1(); 
    } 
+2

我建议你第一次开始使用调试和试找出你的代码中你有什么问题的线..也是这是一个Web应用程序..?或者一个winforms应用程序..?你的代码可以使用一些严重的重构和清理,我也会开始阅读/研究如何为所有的Sql对象使用'using(){}'语句以及清理DataTable对象。 。我个人会在类级别声明...清理你的代码格式在这里也是非常混乱的 – MethodMan

+0

当你有一个DataGridView,并且你有查询无论是否返回数据或不..你可以得到列数基于DataTable.Columns.Count一旦它的DataBind()方法已被调用..也为什么你有'InitializeComponent();'在你的ReadSQL()方法' – MethodMan

+0

我没有收到尝试获取dataGridView1的错误。 ColumnCount,那么调试器有什么好处?这是一个使用Visual Studio的WinForms应用程序。你能否详细说明“严重重构”和“清理”?不确定你在这里的意思。我并不担心在这一点上清理DataTable对象,我所要做的就是获取此方法来确认dataGridView的存在,而不是。不要担心这个问题以外的问题,因为这超出了这个问题的范围。 –

回答

1

这里要说的是,你可以用它来使调用存储过程更好的静态类也许你可以利用和借鉴它

//If you want to return a DataSet 
public static class SqlDBHelper 
{ 
    public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters) 
    { 
     using (DataSet ds = new DataSet()) 
     using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString)) 
     using (SqlCommand cmd = new SqlCommand(sql, connStr)) 
     { 
      cmd.CommandType = cmdType; 
      foreach (var item in parameters) 
      { 
       cmd.Parameters.Add(item); 
      } 

      try 
      { 
       cmd.Connection.Open(); 
       new SqlDataAdapter(cmd).Fill(ds); 
      } 
      catch (Exception ex) 
      { 
       //throw; trap for you exception(s) here 
      } 
      return ds; 
     } 
    } 

    //if you want to return a DataTable  
    public static DataTable ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters) 
    { 
     using (DataSet ds = new DataSet()) 
     using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString)) 
     using (SqlCommand cmd = new SqlCommand(sql, connStr)) 
     { 
      cmd.CommandType = cmdType; 
      foreach (var item in parameters) 
      { 
       cmd.Parameters.Add(item); 
      } 

      try 
      { 
       cmd.Connection.Open(); 
       new SqlDataAdapter(cmd).Fill(ds); 
      } 
      catch (Exception ex) 
      { 
       //Show a message or log a message on ex.Message 
      } 
      return ds.Tables[0]; 
     } 
    } 

} 
+0

你不应该以这种方式在catch块中使用'throw ex'。您应该使用'throw;'来代替,因为它保留了调用堆栈。但无论如何,这样一个低级别的调用没有业务捕捉和重新抛出错误,因为在这个级别上,你不可能决定如何从异常中恢复。 – mason