在dataGridView的单元格中搜索文本并高亮显示该行?

问题描述 投票:1回答:1

我试图实现一个搜索功能,当用户在文本框(tbPartNum)中输入文本,然后点击 "查找 "按钮,它就会搜索dataGridView1中的单元格,一旦找到,它就会将整行高亮显示为黄色。我的代码如下,这显然是不工作的,它抛出了一个错误,它说:"NullReferenceException"。

"NullReferenceException was unhandled."

而在它下面,

"对象引用未被设置为对象的实例"

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;

namespace GBstock
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // populate the dataGridView with the Excel File
            string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", @"C:\Documents and Settings\rghumra\Desktop\Visual Studio\GBstock\GBstock\bin\Debug\FORM TEST.xlsx");
            string query = String.Format("select * from [{0}$]", "Sheet1");
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
            dataGridView1.DataSource = dataSet.Tables[0];

            // populates the comboBox (cbSuppList) with all column headers
            foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                    cbSuppList.Items.Add(col.HeaderText);
            }
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            // Code to search the  alphanumneric Part Number (in Column1 header called "PART NUMBER") and highlihgt the row
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells["PART NUMBER"].Value.ToString().Equals(tbPartNum.Text))
                {
                    dataGridView1.Rows[row.Index].DefaultCellStyle.BackColor = Color.Yellow;
                }
            }
        }

        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Instructions instructionForm = new Instructions();
            instructionForm.Show();
        }

        private void partToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewPart newPartForm = new NewPart();
            newPartForm.Show();
        }

        private void supplierToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewSupplier newSuppForm = new NewSupplier();
            newSuppForm.Show();
        }
    }
}
c# search datagridview find
1个回答
4
投票

NullReferenceException 你所遇到的问题很可能是由于你的网格中包含了 null 单元格值,在 foreach 的查找处理程序。试着修改下面一行。

if (row.Cells["PART NUMBER"].Value.ToString().Equals(tbPartNum.Text))

改成

var cellValue = row.Cells["PART NUMBER"].Value;
if (cellValue != null && cellValue.ToString() == tbPartNum.Text)
© www.soinside.com 2019 - 2024. All rights reserved.