2015-07-24 2 views
0

У меня есть форма с двумя DataGridViews. Выбор строки на одной сетке фильтрует и показывает связанные строки во второй сетке. Теперь, когда я нажимаю, чтобы добавить или отредактировать строку во второй сетке, появится диалоговая форма, и сразу после этого выбор в первой сетке сбрасывается в первую строку отдельно. Почему это происходит и как я могу это предотвратить? Я не смог найти что-то в этом в Интернете.DataGridViewRow.CurrentRow сбрасывается в первую строку

Screenshot

это то, что происходит, когда я нажимаю кнопку Edit во второй сетке. p.s .: grid 1 - currencyGrid, grid 2 - ratesGrid. Когда появляется диалоговое окно редактирования, он переходит в правую строку, но сразу после этого currentRow первой сетки немедленно изменяется на первую строку.

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Data.Sql; 
using System.Data.SqlClient; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Globalization; 
using System.Xml; 
using System.Threading; 

namespace ProjectPro 
{ 
    public partial class CurrenciesAndRates : Form 
    { 
     public CurrenciesAndRates() 
     { 
      InitializeComponent(); 
      this.WindowState = FormWindowState.Minimized; 
      this.WindowState = FormWindowState.Maximized; 
     } 

     private void CurrenciesAndRates_Load(object sender, EventArgs e) 
     {  
      DAL dal = new DAL(); 

      //load Currencies table 
      //load CurrencyRates table 

      try 
      { 
       dal.GetData("Currencies"); 
       dal.GetData("CurrencyRates"); 

       this.currencyGrid.DataSource = StaticValues.dataSet.Tables["Currencies"]; 

       if(this.currencyGrid.Rows.Count > 0) 
       { 
        this.currencyGrid.Rows[0].Selected = true; 
       } 
      } 
      catch (Exception ex) 
      { 
       StaticValues.WriteEventLogXML(ex, this.Text); 
       switch (StaticValues.user.Language) 
       { 
        case "English": 
         MessageBox.Show("Database error", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        case "Russian": 
         MessageBox.Show("Ошибка базы данных", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        case "Azeri": 
         MessageBox.Show("Məlumat bazası səhvi", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        default: 
         break; 
       } 
      } 
     } 

     private void currenciesGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
     { 

     } 

     private void dateTimePicker1_ValueChanged(object sender, EventArgs e) 
     { 
      DAL dal = new DAL(); 

      try 
      { 
       dal.GetData("Currencies"); 
       dal.GetData("CurrencyRates"); 
       dal.GetCurrencyRatesAtDate(dateTimePicker1.Value); 
      } 
      catch (Exception ex) 
      { 
       StaticValues.WriteEventLogXML(ex, this.Text); 
       switch (StaticValues.user.Language) 
       { 
        case "English": 
         MessageBox.Show("Database error", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        case "Russian": 
         MessageBox.Show("Ошибка базы данных", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        case "Azeri": 
         MessageBox.Show("Məlumat bazası səhvi", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        default: 
         break; 
       } 
      } 
     } 

     private void currencyGrid_CellClick(object sender, DataGridViewCellEventArgs e) 
     { 
      switch(StaticValues.user.Language) 
      { 
       case "English": 
        historyForLab.Text = "History for " + currencyGrid.CurrentRow.Cells["Code"].Value.ToString() + ":"; 
        break; 
       case "Russian": 
        historyForLab.Text = "История по " + currencyGrid.CurrentRow.Cells["Code"].Value.ToString() + ":"; 
        break; 
       case "Azeri": 
        historyForLab.Text = currencyGrid.CurrentRow.Cells["Code"].Value.ToString() + " üzrə tarixçə:"; 
        break; 
       default: 
        break; 
      } 

      DataView dv = StaticValues.dataSet.Tables["CurrencyRates"].DefaultView; 
      dv.RowFilter = "CurrencyID = '" + currencyGrid.CurrentRow.Cells["ID"].Value.ToString() + "'"; 
      dv.Sort = "Date DESC"; 

      this.ratesGrid.DataSource = dv; 
      this.ratesGrid.Columns[0].Visible = false; 
      this.ratesGrid.Columns[2].Visible = false; 

      StaticValues.LocalizeGrid(this.ratesGrid, "CurrencyRates"); 
     } 

     private void currencyGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
     { 
      if(!currencyGrid.Columns.Contains("Rate")) 
       currencyGrid.Columns.Add("Rate", "Rate"); 

      foreach (DataGridViewRow currencyRow in currencyGrid.Rows) 
      { 
       foreach (DataRow row in StaticValues.dataSet.Tables["CurrencyRates"].Rows) 
       { 
        if (row["CurrencyID"].ToString() == currencyRow.Cells["ID"].Value.ToString() && 
         DateTime.Parse(row["Date"].ToString()).ToShortDateString() == dateTimePicker1.Value.ToShortDateString()) 
        { 
         currencyRow.Cells["Rate"].Value = row["Rate"].ToString(); 
         break; 
        } 
       } 
      } 
     } 

     private void GetCurrentRatesFromCBAR() 
     { 
      string url = "http://cbar.az/currencies/" + DateTime.Now.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) + ".xml"; 

      try 
      { 
       XmlDocument doc = new XmlDocument(); 
       doc.Load(url); 

       XmlElement root = doc.DocumentElement; 
       XmlNodeList nodes = root.SelectNodes("//ValCurs/ValType"); 

       DataTable tempRates = new DataTable(); 

       foreach (XmlNode node in nodes) 
       { 
        if (node.Attributes["Type"].Value == "Xarici valyutalar") 
        { 
         //create temp table and load new rates 
         tempRates.Clear(); 
         tempRates.Columns.Add("Code"); 
         tempRates.Columns.Add("Nominal"); 
         tempRates.Columns.Add("Name"); 
         tempRates.Columns.Add("Value"); 

         foreach (XmlNode currency in node.ChildNodes) 
         { 
          DataRow dr = tempRates.NewRow(); 
          dr["Code"] = currency.Attributes["Code"].Value; 

          foreach (XmlNode currencyDetailsNode in currency.ChildNodes) 
          { 
           dr[currencyDetailsNode.Name] = currencyDetailsNode.InnerText; 
          } 

          tempRates.Rows.Add(dr); 
         } 
        }      
       } 

       //write new rates to the database 
       ///delete records in Rates table with the current date 
       DAL dal = new DAL(); 
       dal.ClearCurrentRates(DateTime.Now); 

       //insert new values 
       foreach (DataRow currencyRow in StaticValues.dataSet.Tables["Currencies"].Rows) 
       { 
        if(currencyRow["Code"].ToString() == "AZN") 
        { 
         #region Insert the row for AZN 
         try 
         { 
          SqlParameter[] pars = new SqlParameter[3]; 

          pars[0] = new SqlParameter("@Date", SqlDbType.Date); 
          pars[0].Value = DateTime.Now.Date.ToShortDateString(); 

          pars[1] = new SqlParameter("@CurrencyID", SqlDbType.Int); 
          pars[1].Value = currencyRow["ID"].ToString(); 

          pars[2] = new SqlParameter("@Rate", SqlDbType.Decimal); 
          pars[2].Value = 1.0000; 

          dal.InsertData("CurrencyRates", pars); 
         } 
         catch (Exception ex) 
         { 
          StaticValues.WriteEventLogXML(ex, this.Text); 
          switch (StaticValues.user.Language) 
          { 
           case "English": 
            MessageBox.Show("Database error", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
            break; 
           case "Russian": 
            MessageBox.Show("Ошибка базы данных", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
            break; 
           case "Azeri": 
            MessageBox.Show("Məlumat bazası səhvi", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
            break; 
           default: 
            break; 
          } 
         } 
         #endregion 
         continue; 
        } 
        foreach (DataRow tempRow in tempRates.Rows) 
        { 
         if (tempRow["Code"].ToString() == currencyRow["Code"].ToString()) 
         { 
          #region Insert the row 
          try 
          { 
           SqlParameter[] pars = new SqlParameter[3]; 

           pars[0] = new SqlParameter("@Date", SqlDbType.Date); 
           pars[0].Value = DateTime.Now.Date.ToShortDateString(); 

           pars[1] = new SqlParameter("@CurrencyID", SqlDbType.Int); 
           pars[1].Value = currencyRow["ID"].ToString(); 

           pars[2] = new SqlParameter("@Rate", SqlDbType.Decimal); 
           pars[2].Value = decimal.Parse(tempRow["Value"].ToString(), CultureInfo.InvariantCulture); 

           dal.InsertData("CurrencyRates", pars); 
           break; 
          } 
          catch (Exception ex) 
          { 
           StaticValues.WriteEventLogXML(ex, this.Text); 
           switch (StaticValues.user.Language) 
           { 
            case "English": 
             MessageBox.Show("Database error", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
             break; 
            case "Russian": 
             MessageBox.Show("Ошибка базы данных", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
             break; 
            case "Azeri": 
             MessageBox.Show("Məlumat bazası səhvi", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
             break; 
            default: 
             break; 
           } 
           break; 
          } 
          #endregion 
         } 
        } 
       } 

       this.CurrenciesAndRates_Load(this, null); 
      } 
      catch (Exception ex) 
      { 
       StaticValues.WriteEventLogXML(ex, this.Text); 
       switch (StaticValues.user.Language) 
       { 
        case "English": 
         MessageBox.Show("XML error", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        case "Russian": 
         MessageBox.Show("Ошибка XML", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        case "Azeri": 
         MessageBox.Show("XML səhvi", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        default: 
         break; 
       } 
      } 


     } 

     private void getTodaysRatesToolStripMenuItem_Click(object sender, EventArgs e) 
     { 
      this.GetCurrentRatesFromCBAR(); 
     } 

     private void getRatesForAPeriodToolStripMenuItem_Click(object sender, EventArgs e) 
     { 
      GetRatesForPeriod getRates = new GetRatesForPeriod(); 
      getRates.ShowDialog(); 
     } 

     private void getRatesToolStripSplitButton_ButtonClick(object sender, EventArgs e) 
     { 
      getRatesToolStripSplitButton.ShowDropDown(); 
     } 


     private void gridDtp_ValueChanged(object sender, EventArgs e) 
     { 
      ratesGrid.CurrentCell.Value = gridDtp.Value.Date; 
      gridDtp.Visible = false; 
     } 

     private void addRateBut_Click(object sender, EventArgs e) 
     { 
      string id = this.currencyGrid.CurrentRow.Cells[1].Value.ToString(); 

      if (this.currencyGrid.CurrentRow != null) 
      { 
       AddEditRates rate = new AddEditRates(this.currencyGrid.CurrentRow.Cells[2].Value.ToString(), false, null, this, this.currencyGrid.CurrentCell.OwningColumn.Index, this.currencyGrid.CurrentRow.Index); 
       if (rate.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
       { 

       } 
      } 
     } 

     private void editRateBut_Click(object sender, EventArgs e) 
     { 
      if(this.ratesGrid.CurrentRow != null) 
      { 
       AddEditRates rate = new AddEditRates(this.currencyGrid.CurrentRow.Cells[2].Value.ToString(), true, this.ratesGrid.CurrentRow, this, this.currencyGrid.CurrentCell.OwningColumn.Index, this.currencyGrid.CurrentRow.Index); 
       if(rate.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
       { 

       } 
      } 
     } 

     private void CurrenciesAndRates_FormClosing(object sender, FormClosingEventArgs e) 
     { 
      MainForm parent = (MainForm)this.MdiParent; 

      if (parent.mdiChildList.Items.Contains(this.Text)) 
      { 
       parent.mdiChildList.Items.Remove(this.Text); 
      } 
     } 

     private void CurrenciesAndRates_Activated(object sender, EventArgs e) 
     { 
      MainForm parent = (MainForm)this.MdiParent; 

      for (int i = 0; i < parent.mdiChildList.Items.Count; i++) 
      { 
       if (parent.mdiChildList.Items[i].ToString() == this.Text) 
       { 
        parent.mdiChildList.SelectedIndex = i; 
        break; 
       } 
      } 
     } 
    } 
} 

И это код диалогового формы, которая называется на «добавить» и «редактировать»:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace ProjectPro 
{ 
    public partial class AddEditRates : Form 
    { 
     public AddEditRates(string currencyCode, bool isEdit, DataGridViewRow currentRow, CurrenciesAndRates form, int colIndex, int rowIndex) 
     { 
      InitializeComponent(); 

      this.edit = isEdit; 
      this.row = currentRow; 
      this.currency = currencyCode; 
      this.parentForm = form; 

      foreach(DataGridViewRow row in parentForm.currencyGrid.Rows) 
      { 
       if(row.Cells[2].Value.ToString() == this.currency) 
       { 
        this.parentForm.currencyGrid.ClearSelection(); 
        row.Selected = true; 
        break; 
       } 
      } 

      this.Text = StaticValues.SetCaption(this.Text, this.edit); 
     } 

     bool edit; 
     DataGridViewRow row; 
     string currency; 
     CurrenciesAndRates parentForm; 
     private void AddEditRates_Load(object sender, EventArgs e) 
     { 
      // set values for the fields 


      if (this.edit) 
      { 
       this.date.Value = DateTime.Parse(this.row.Cells[1].Value.ToString(), Application.CurrentCulture); 
       this.rateTB.Text = this.row.Cells[3].Value.ToString(); 
      } 
      else 
       this.date.Value = DateTime.Today; 

      try 
      { 
       DAL dal = new DAL(); 
       dal.GetData("Currencies"); 

       //populate currencies comboBox 
       if (StaticValues.dataSet.Tables.Contains("Currencies")) 
       { 
        currencyCB.DataSource = StaticValues.dataSet.Tables["Currencies"]; 
        currencyCB.DisplayMember = "Code"; 
       } 

       this.currencyCB.Text = this.currency; 
      } 
      catch (Exception ex) 
      { 
       StaticValues.WriteEventLogXML(ex, this.Text); 
       switch (StaticValues.user.Language) 
       { 
        case "English": 
         MessageBox.Show("Database error", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        case "Russian": 
         MessageBox.Show("Ошибка базы данных", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        case "Azeri": 
         MessageBox.Show("Məlumat bazası səhvi", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
         break; 
        default: 
         break; 
       } 
      } 
     } 

     private void cancelBut_Click(object sender, EventArgs e) 
     { 
      this.Close(); 
     } 
    } 
} 
+0

Вы можете поделиться своими кодами? –

+0

проверить события DataGidView. –

+0

, пожалуйста, проверьте обновление до моего сообщения. –

ответ

0

Ну, это была моя ошибка ... Я обнаружил, что я перезарядил таблицу из формы диалога, которая фактически была источником данных для моей первой сетки, поэтому сетка была обновлена ​​и повторно отображена.

Смежные вопросы