在Datagridview中搜索数据

时间:2016-02-15 18:50:19

标签: c# datagridview

我试图在我的DataGridView中搜索数据,以便只在文本框中显示包含所选文本的行,但是当我键入它时,它会完全删除数据。我在MSDN上使用了我的代码示例:https://code.msdn.microsoft.com/windowsdesktop/Search-Data-From-Database-f2cb5d53

这是我的代码:

     private void txtbox_TextChanged(object sender, EventArgs e)
     {
        DataView DV = new DataView(datatable);
        DV.RowFilter = string.Format("Name LIKE '%{0}%'", txtbox.Text);
        dataGridView1.DataSource = DV; 
     }

在: enter image description here

在: enter image description here

任何帮助都将不胜感激,谢谢。

注意:我没有使用SQL,只有C#

整件事:命名空间CsvFileTest {     公共部分类Form1:表格     {         private const int MaxColumns = 64;         受保护的字符串FileName;         protected bool修改;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        InitializeGrid();
        ClearFile();
    }

    private void newToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (SaveIfModified())
            ClearFile();
    }

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (SaveIfModified())
        {
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                ReadFile(openFileDialog1.FileName);
        }
    }

    private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (FileName != null)
            WriteFile(FileName);
        else
            saveAsToolStripMenuItem_Click(sender, e);
    }

    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        saveFileDialog1.FileName = FileName;
        if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
            WriteFile(saveFileDialog1.FileName);
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (SaveIfModified())
            Close();
    }

    /// <summary>
    /// //////////////////////////////////////////////
    /// </summary>

    private void InitializeGrid()
    {
        for (int i = 1; i <= MaxColumns; i++)
        {
            dataGridView1.Columns.Add(
                String.Format("Column{0}", i),
                String.Format("Column {0}", i));
        }
    }

    private void ClearFile()
    {
        dataGridView1.Rows.Clear();
        FileName = null;
        Modified = false;
    }

    private bool ReadFile(string filename)
    {
        Cursor = Cursors.WaitCursor;
        try
        {
            //dataGridView1.Rows.Clear();
            List<string> columns = new List<string>();
            using (var reader = new CsvFileReader(filename))
            {
                while (reader.ReadRow(columns))
                {
                    dataGridView1.Rows.Add(columns.ToArray());
                }
            }
            FileName = filename;
            Modified = false;
            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(String.Format("Error reading from {0}.\r\n\r\n{1}", filename, ex.Message));
        }
        finally
        {
            Cursor = Cursors.Default;
        }
        return false;
    }

    private bool WriteFile(string filename)
    {
        Cursor = Cursors.WaitCursor;
        try
        {
            // Like Excel, we'll get the highest column number used,
            // and then write out that many columns for every row
            int numColumns = GetMaxColumnUsed();
            using (var writer = new CsvFileWriter(filename))
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        List<string> columns = new List<string>();
                        for (int col = 0; col < numColumns; col++)
                            columns.Add((string)row.Cells[col].Value ?? String.Empty);
                        writer.WriteRow(columns);
                    }
                }
            }
            FileName = filename;
            Modified = false;
            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(String.Format("Error writing to {0}.\r\n\r\n{1}", filename, ex.Message));
        }
        finally
        {
            Cursor = Cursors.Default;
        }
        return false;
    }

    // Determines the maximum column number used in the grid
    private int GetMaxColumnUsed()
    {
        int maxColumnUsed = 0;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (!row.IsNewRow)
            {
                for (int col = row.Cells.Count - 1; col >= 0; col--)
                {
                    if (row.Cells[col].Value != null)
                    {
                        if (maxColumnUsed < (col + 1))
                            maxColumnUsed = (col + 1);
                        continue;
                    }
                }
            }
        }
        return maxColumnUsed;
    }

    private bool SaveIfModified()
    {
        if (!Modified)
            return true;

        DialogResult result = MessageBox.Show("The current file has changed. Save changes?", "Save Changes", MessageBoxButtons.YesNoCancel);
        if (result == DialogResult.Yes)
        {
            if (FileName != null)
            {
                return WriteFile(FileName);
            }
            else
            {
                saveFileDialog1.FileName = FileName;
                if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
                    return WriteFile(saveFileDialog1.FileName);
                return false;
            }
        }
        else if (result == DialogResult.No)
        {
            return true;
        }
        else // DialogResult.Cancel
        {
            return false;
        }
    }

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        Modified = true;
    }
    protected static DataView dv = null;//declared at the Class Level
    protected static DataTable dtSearch = null;
    public static DataTable dtCrossTab { get; set; }

    private void button1_Click(object sender, EventArgs e)
    {

        if (txtbox.Text.Length > 0)
        {
            dtSearch = dtCrossTab;//this is the original datatable
            dv = new DataView(dtSearch);//assigning the dtSearch to dv object
            dv.RowFilter = "NAME 4 LIKE '%" + txtbox.Text.ToUpper() + "%'";

        }
        else
        {
            dtSearch = null;
            dv = null;
        }
    }

1 个答案:

答案 0 :(得分:1)

分配给DataSource时,您将整个数据源分配给GridView。 我建议您有一个列表或集合,其中包含所有数据。我有这个例子:

IEnumerable<Product> ListProduct = from Prod in LstProducts where Prod.Description.StartsWith(txtFind.Text) select Prod;
        dataGridView1.Rows.Clear();
        foreach (var item in ListProduct)
        {
            this.dataGridView1.Rows.Add(item.Id, item.Status, item.Description, tipo.Price);
        }

过滤所需列中的信息(描述)并使用所需的过滤器(StartsWith),但为此需要有一个对象列表(LstProducts)。我希望它有所帮助。

编辑。您的代码现在看起来像

private void txtbox_TextChanged(object sender, EventArgs e)
 {
    DataView DV = new DataView(datatable);
    DV.RowFilter = string.Format("ColumnX LIKE '%{0}%'", txtbox.Text);
    dataGridView1.DataSource = DV; 
 }

其中X是您要过滤的列的编号。如果您想要更多控制,我建议您更改列ID,名称,描述等的名称。