C#DataGridView过滤器可以工作,但在使用过滤器之后,所选行不会返回正确的数据

时间:2011-08-18 20:11:41

标签: c# datagridview rowfilter

我已经接管了某人的计划。所以这是我第一次处理DataViewGrid。

数据完美填充。当用户选择一行时,它会填充表单中的文本框。我不确定那部分是如何工作的,因为没有任何说法

txtEmail.text = 

或在此表单中的任何位置选择行。但是没关系......如果它有效,我会处理。

这是我的问题。我添加了一个过滤器。这很棒。在您键入时,它会过滤匹配的每一行。

private void txtSearch_TextChanged(object sender, EventArgs e) 
{

     DataView dv = new DataView(this.dsFavoritesList.gryFavoritesList);
     dv.Sort = "Name ASC";

     dv.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);
     dataGridView1.DataSource = dv;
}

但现在只要在过滤器中输入任何内容,选中的任何行都不会填充文本框。直到我重新加载整个表单,我才能再次正确选择任何内容。

如果我开始明白......我已经更新了gridview而不是源代码......我只是不知道如何。

谢谢! -Matt

整体表格

在设计器视图中,我有3个文本框。 txtEmail,txtName,txtImageCount在我进行新选择时填充。但是,一旦我过滤了datagridview,就会在我尝试选择行时填充框。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using Ini;
using System.Configuration;
using System.Threading;



namespace UpLoadImages
{
    public partial class CopyFavorites : Form
    {
        public CopyFavorites()
        {
            InitializeComponent();
    }

    private void CopyFavorites_Load(object sender, EventArgs e)
    {
        try
        {
            // get the default values
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            IniFile ini = new IniFile(string.Format(@"{0}\gift.ini", appPath));

            txtEventsDrive.Text = ini.IniReadValue("Info", "LocationOfEvents");
            txtHiResTarget.Text = ini.IniReadValue("Info", "FavWorkSpace");
            this.StartPosition = FormStartPosition.CenterScreen;
            oleDbConnection1.ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];

            backgroundWorker1.RunWorkerAsync();
            //commented out so we can try it as a background worker
            // TODO: This line of code loads data into the 'dsFavoritesList.gryFavoritesList' table. You can move, or remove it, as needed.
            //this.gryFavoritesListTableAdapter.Fill(this.dsFavoritesList.gryFavoritesList);

            ProgressPanel.Visible = false;
            txtSearch.Focus();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btnCopy_Click(object sender, EventArgs e)
    {
        this.MdiParent.MainMenuStrip.Enabled = false;

        try
        {
            string strError = CopyImages();



            StringBuilder sql = new StringBuilder();

            sql.AppendFormat("UPDATE FavoritesHeader SET FavoritesHeader.FilesCopied = {0} ", Convert.ToInt32(txtImagesCopied.Text));
            sql.AppendFormat("WHERE FavoritesHeader.EmailAddress='{0}'", txtEmail.Text);
            UpdateDatabase(sql.ToString());


            this.gryFavoritesListTableAdapter.Fill(this.dsFavoritesList.gryFavoritesList);


            MessageBoxButtons buttons = MessageBoxButtons.OK;
            MessageBox.Show(this, strError, "Copy Images", buttons, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);

            ProgressPanel.Visible = false;
        }


        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            this.MdiParent.MainMenuStrip.Enabled = true;
        }




    }
    private string CopyAllImages()
    {
        StringBuilder strError = new StringBuilder();
        string clr = "\r\n";
        strError.AppendFormat("Time started: {0}{1}{1}", DateTime.Now.ToLongTimeString(), clr);
        try
        {


            StringBuilder str = new StringBuilder();
            str.AppendFormat("Select FavoritesHeader.EmailAddress,  StrConv([LastName],1)+'_'+StrConv([firstname],3) AS Folder, FavoritesDetail.ImagePath,MainEvents.MainEventCode, ");
            str.AppendFormat("FavoritesDetail.ImageName FROM (FavoritesHeader INNER JOIN MainEvents ON FavoritesHeader.MainEventID = MainEvents.MainEventID) ");
            str.AppendFormat("LEFT JOIN FavoritesDetail ON FavoritesHeader.FavoritesHeaderID = FavoritesDetail.FavoritesHeaderID ");
            str.AppendFormat(" WHERE (((MainEvents.isActive)=1)) ");
            str.AppendFormat(" ORDER BY FavoritesHeader.EmailAddress,  StrConv([LastName],1)+'_'+StrConv([firstname],3), FavoritesDetail.ImagePath");

            DataTable dt_Images = GetDataTable(str.ToString());
            int maxFiles = dt_Images.Rows.Count;

            strError.AppendFormat("Images to copy: {0}{1}{1}", maxFiles, clr);
            Application.DoEvents();


            progressBar.Maximum = maxFiles;
            progressBar.Value = 0;
            ProgressPanel.Visible = true;


            string strTarget = string.Empty;
            int i = 0;

            foreach (DataRow row in dt_Images.Rows)
            {
                i = i + 1;
                progressBar.Value = i;

                ProgressCount.Text = string.Format("Files Copied: {0} of {1}", i, maxFiles);
                Application.DoEvents();

                string path = row["ImagePath"] as string;
                path = path.Replace(@"Thumbs", @"Preview");
                //string folder = row["Folder"].ToString().Replace("@", "_").Replace(".", "_");
                string folder = row["Folder"].ToString();//.Replace("@", "_").Replace(".", "_");


                strTarget = string.Format(@"{0}\Favorites_{1}\{2}", txtHiResTarget.Text, row["MainEventCode"] as string, folder);
                if (!System.IO.Directory.Exists(strTarget))
                {
                    // create the directory
                    System.IO.Directory.CreateDirectory(strTarget);
                }
                string destFileName = string.Format(@"{0}\{1}", strTarget, row["ImageName"] as string);
                string sourceFileName = string.Format(@"{0}\{1}", txtEventsDrive.Text, path);
                sourceFileName = sourceFileName.Replace(@"/", @"\");
                sourceFileName = sourceFileName.Replace(@"\\", @"\");
                try
                {
                    System.IO.File.Copy(sourceFileName, destFileName,true);
                }
                catch (Exception ex)
                {
                    strError.AppendFormat("{0}{1}{1}", ex.Message, clr);
                }
            }
            //DirectoryInfo dir3 = new DirectoryInfo(strTarget);
            //txtImagesCopied.Text = Convert.ToString(dir3.GetFiles("*.jpg").Length);
            //strError.AppendFormat("Images in destination: {0}{1}{1}", txtImagesCopied.Text, clr);
            strError.AppendFormat("Time Ended: {0}{1}{1}", DateTime.Now.ToLongTimeString(), clr);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return strError.ToString();


    }
    private string CopyImages()
    {
        StringBuilder strError = new StringBuilder();
        string clr = "\r\n";
        strError.AppendFormat("Time started: {0}{1}{1}", DateTime.Now.ToLongTimeString(), clr);
        try
        {

            StringBuilder str = new StringBuilder();
            str.AppendFormat("SELECT FavoritesHeader.EmailAddress, MainEvents.MainEventCode, FavoritesDetail.ImagePath, ");
            str.AppendFormat("FavoritesDetail.ImageName FROM (FavoritesHeader LEFT JOIN FavoritesDetail ON ");
            str.AppendFormat("FavoritesHeader.FavoritesHeaderID = FavoritesDetail.FavoritesHeaderID) INNER JOIN ");
            str.AppendFormat(" MainEvents ON FavoritesHeader.MainEventID = MainEvents.MainEventID WHERE ");
            str.AppendFormat(" FavoritesHeader.EmailAddress='{0}' AND MainEvents.isActive=1", txtEmail.Text);

            DataTable dt_Images = GetDataTable(str.ToString());
            int maxFiles = dt_Images.Rows.Count;

            strError.AppendFormat("Images to copy: {0}{1}{1}", maxFiles, clr);
            Application.DoEvents();


            progressBar.Maximum = maxFiles;
            progressBar.Value = 0;
            ProgressPanel.Visible = true;


            string strTarget = string.Empty;
            int i = 0;
            int AlreadyExists = -1;
            int ExistsIndex = 0;

            foreach (DataRow row in dt_Images.Rows)
            {
                i = i + 1;
                progressBar.Value = i;

                ProgressCount.Text = string.Format("Files Copied: {0} of {1}", i, maxFiles);
                Application.DoEvents();

                string path = row["ImagePath"] as string;
                path = path.Replace(@"Thumbs", @"HiRes");
                string eMail = txtEmail.Text.ToString().Replace("@", "_").Replace(".", "_");

                strTarget = string.Format(@"{0}\{1}_MainEvent\FavoriteCD\{2}", txtHiResTarget.Text, row["MainEventCode"] as string, eMail);
                if (!System.IO.Directory.Exists(strTarget))
                {
                    // create the directory
                    System.IO.Directory.CreateDirectory(strTarget);
                }
                string destFileName = string.Format(@"{0}\{1}", strTarget, row["ImageName"] as string);
                string sourceFileName = string.Format(@"{0}\{1}", txtEventsDrive.Text, path);
                sourceFileName = sourceFileName.Replace(@"/", @"\");
                //sourceFileName = sourceFileName.Replace(@"\\", @"\");
                try
                {
                    System.IO.File.Copy(sourceFileName, destFileName);
                }
                catch (Exception ex)
                {
                    AlreadyExists = (strError.ToString()).IndexOf("already exists");
                    if (AlreadyExists == -1)
                    {
                        strError.AppendFormat("{0}{1}{1}", ex.Message, clr);
                    }
                    else
                    {
                        ExistsIndex = ExistsIndex + AlreadyExists;
                    }

                }
            }

            if (ExistsIndex > 0)
            {
                strError.AppendFormat("Some files were copied previously{0}", clr);
            }

            DirectoryInfo dir3 = new DirectoryInfo(strTarget);
            txtImagesCopied.Text = Convert.ToString(dir3.GetFiles("*.jpg").Length);
            strError.AppendFormat("Images in destination: {0}{1}{1}", txtImagesCopied.Text, clr);
            strError.AppendFormat("Time Ended: {0}{1}{1}", DateTime.Now.ToLongTimeString(), clr);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return strError.ToString();


    }

    private void UpdateDatabase(string sql)
    {
        OleDbConnection sqlConnNew = new OleDbConnection();
        sqlConnNew.ConnectionString = oleDbConnection1.ConnectionString;

        sqlConnNew.Open();

        OleDbCommand oleCMD = new OleDbCommand();
        oleCMD.Connection = sqlConnNew;
        OleDbTransaction oleTrans = oleCMD.Connection.BeginTransaction();
        oleCMD.Transaction = oleTrans;
        oleCMD.CommandText = sql;
        try
        {
            oleCMD.ExecuteNonQuery();
            oleTrans.Commit();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        oleCMD.Connection.Close();
        oleCMD.Dispose();
    }
    public DataTable GetDataTable(string sql)
    {
        DataTable RS = new DataTable();
        try
        {
            OleDbConnection sqlConnNew = new OleDbConnection();
            sqlConnNew.ConnectionString = oleDbConnection1.ConnectionString;

            sqlConnNew.Open();

            OleDbCommand oleCMD = new OleDbCommand(sql, sqlConnNew);
            OleDbDataAdapter oleAdr = new OleDbDataAdapter(oleCMD);
            oleAdr.AcceptChangesDuringFill = true;
            oleAdr.Fill(RS);
            oleCMD.Connection.Close();
            oleCMD.Dispose();
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        return RS;
    }

    private void SaveDefaults_Click(object sender, EventArgs e)
    {
        try
        {
            // get the application path to find the ini file
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            IniFile ini = new IniFile(string.Format(@"{0}\gift.ini", appPath));

            ini.IniWriteValue("Info", "LocationOfEvents", txtEventsDrive.Text);
            ini.IniWriteValue("Info", "FavWorkSpace", txtHiResTarget.Text);
            MessageBox.Show("Defaults settings have been saved.", "Save Defaults");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

    private void Exit_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void About_Click(object sender, EventArgs e)
    {
        AboutBox MyAboutBox = new AboutBox();
        MyAboutBox.ShowDialog();
    }

    private void getInvoiceToolStripMenuItem_Click(object sender, EventArgs e)
    {
        this.Hide();
        GetInvoice getInvoice = new GetInvoice();
        getInvoice.ShowDialog();

    }

    private void processImagesToolStripMenuItem_Click(object sender, EventArgs e)
    {
        this.Hide();
        ProcessImages processImages = new ProcessImages();
        processImages.ShowDialog();
    }

    private void btnRefresh_Click(object sender, EventArgs e)
    {
        lblLoadingData.Visible = true;
        this.gryFavoritesListTableAdapter.Fill(this.dsFavoritesList.gryFavoritesList);
        dataGridView1.Refresh();
    }




    private void txtSearch_TextChanged(object sender, EventArgs e)
    {

        DataView dv = new DataView(this.dsFavoritesList.gryFavoritesList);
        dv.Sort = "Name ASC";

        dv.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);
        dataGridView1.DataSource = dv;


        //if (index == -1)
        //{
        //    MessageBox.Show("No PK matches " + txtSearch.Text);
        //}
        //else
        //{


        //    dataGridView1.FirstDisplayedScrollingRowIndex = index;
        //    dataGridView1.Refresh();
        //    dataGridView1.CurrentCell = dataGrid.Rows[index].Cells[0];
        //    dataGridView1.Rows[index].Selected = true;

            //dataGridView1.CurrentRowIndex = intRow;                
            //dataGridView1.Select(intRow);
       //}


    }

    private void btnExport_Click(object sender, EventArgs e)
    {

        this.MdiParent.MainMenuStrip.Enabled = false;

        try
        {
            string strError = CopyAllImages();

            MessageBoxButtons buttons = MessageBoxButtons.OK;
            MessageBox.Show(this, strError, "Copy All Favorites", buttons, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);

            ProgressPanel.Visible = false;
        }


        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            this.MdiParent.MainMenuStrip.Enabled = true;
        }

    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            this.gryFavoritesListTableAdapter.Fill(this.dsFavoritesList.gryFavoritesList);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        lblLoadingData.Visible = false;
    }

}

}

1 个答案:

答案 0 :(得分:1)

验证测试来处理事件而不是TextBox TextChanged事件,因为每次插入一个字符都被称为事件,而你在使用Validated时实际执行了txtsearch的验证。

private void txtSearch_Vlidated(object sender, EventArgs e) 

{

 DataView dv = new DataView(this.dsFavoritesList.gryFavoritesList);
 dv.Sort = "Name ASC";

 dv.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);
 dataGridView1.DataSource = dv;

}

问候。