开发者

C# DataGridView Filter works but after using the Filter the selected row doesn't return the right data

开发者 https://www.devze.com 2023-03-28 22:00 出处:网络
I\'ve taken over somebody\'s program.So this is my first time dealing with DataViewGrid. The data populates perfectly.When the user select a row it populates a text box in the form.Which I\'m not sur

I've taken over somebody's program. So this is my first time dealing with DataViewGrid.

The data populates perfectly. When the user select a row it populates a text box in the form. Which I'm not sure how that part is working since there is nothing that says

txtEmail.text = 

Or Selected Row anywhere in this form. But it's ok.. if it works I'll deal.

Here's my issue. I've added a filter. which works great. As you type it filters each row for the matches.

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

But now as soon as you type anything in the filter, any row that is selected does not populate the textbox. It isn't until I reload the entire form that I can select anything properly again.

If I'm beginning to understand... I've update the gridview but not the source.. I just don't know how.

Thanks! -Matt

Whole Form

In the designer view I have 3 text boxes. txtEmail, txtName, txtImageCount that get populated as I make a new selection. But once I filter the datagridview the boxes never get populated as I try to select rows.

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.gryFavor开发者_开发百科itesList);
        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;
    }

}

}


validated test to handle the event instead of the TextBox TextChanged event, because every time you insert a character is called the event, while you search with the Validated when actually carried out the validation of 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;

}

Regards.

0

精彩评论

暂无评论...
验证码 换一张
取 消