DataGridViewRow.CurrentRow重置为第一行

时间:2015-07-24 06:35:20

标签: c# datagridview

我有一个包含两个DataGridViews的表单。选择一个网格上的行过滤并显示第二个网格中的相关行。现在,当我单击以在第二个网格中添加或编辑行时,将出现对话框表单,并在第一个网格中的选择之后立即重置为第一行。为什么会发生这种情况,我该如何预防呢?我没能在网上找到这方面的东西。

Screenshot

当我在第二个网格上单击“编辑”按钮时会发生这种情况。 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;
                }
            }
        }
    }
}

这是对话框表单的代码,它被调用&#39; add&#39;和&#39;编辑&#39;:

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();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这是我的错误......我发现我从对话框表单重新加载了表格,该表格实际上是我的第一个网格的数据源,因此网格已更新并重新渲染。