DataTable dt = (DataTable)dataGridView1.DataSource,dt返回空值的问题

当尝试通过dataGridView1.DataSource获取数据时,DataTable dt可能返回空值。问题在于未先将数据绑定到dataGridView1.DataSource。示例代码展示了在Form1_Load事件中正确绑定数据到dataGridView,而在button2_Click事件中尝试获取数据时遇到空值问题。

有时我们需要将将dataGridView内容放入DataSet或DataTable中,应用:

DataTable dt = (DataTable)dataGridView1.DataSource;或  DataTable dt =  dataGridView1.DataSource as DataTable ;

应用后dt中为空值,主要是因为没有将dataGridView1.DataSource绑定DataTable ;

应用时:

   private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                openSql();
                string strSql = "SELECT * FROM tab where Name='张三'";
                SqlDataAdapter s = new SqlDataAdapter(strSql, strCon);
                s.Fill(dt);
                dataGridView1.DataSource = dt;//绑定
             
 

using System; using System.Data; using System.IO; using System.Linq; using System.Windows.Forms; using OfficeOpenXml; namespace ExcelQueryApp { public partial class MainForm : Form { private DataTable excelData = new DataTable(); public MainForm() { InitializeComponent(); // 设置EPPlus许可证上下文 ExcelPackage.LicenseContext = LicenseContext.NonCommercial; } private void btnOpenFile_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.Filter = "Excel Files|*.xlsx;*.xls"; openFileDialog.Title = "Select an Excel File"; if (openFileDialog.ShowDialog() == DialogResult.OK) { txtFilePath.Text = openFileDialog.FileName; LoadExcelData(openFileDialog.FileName); } } } private void LoadExcelData(string filePath) { try { using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath))) { if (package.Workbook.Worksheets.Count == 0) { MessageBox.Show("Excel文件中没有工作表。"); return; } ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; // 清现有数据 excelData.Clear(); excelData.Columns.Clear(); // 读取列头 int colCount = worksheet.Dimension.End.Column; for (int col = 1; col <= colCount; col++) { excelData.Columns.Add(worksheet.Cells[1, col].Text); } // 读取数据行 int rowCount = worksheet.Dimension.End.Row; for (int row = 2; row <= rowCount; row++) { DataRow dataRow = excelData.NewRow(); for (int col = 1; col <= colCount; col++) { dataRow[col - 1] = worksheet.Cells[row, col].Text; } excelData.Rows.Add(dataRow); } dataGridView.DataSource = excelData; lblStatus.Text = $"已加载 {excelData.Rows.Count} 行数据"; } } catch (Exception ex) { MessageBox.Show($"加载Excel文件时出错: {ex.Message}"); } } private void btnSearch_Click(object sender, EventArgs e) { if (excelData.Rows.Count == 0) { MessageBox.Show("请先打开Excel文件。"); return; } string searchText = txtSearch.Text.Trim(); if (string.IsNullOrEmpty(searchText)) { dataGridView.DataSource = excelData; lblStatus.Text = $"显示全部 {excelData.Rows.Count} 行数据"; return; } // 创建数据视图并过滤 DataView dv = new DataView(excelData); string filterExpression = ""; foreach (DataColumn column in excelData.Columns) { if (filterExpression != "") filterExpression += " OR "; filterExpression += $"[{column.ColumnName}] LIKE '%{searchText}%'"; } dv.RowFilter = filterExpression; dataGridView.DataSource = dv; lblStatus.Text = $"找到 {dv.Count} 条匹配记录"; } private void btnClearSearch_Click(object sender, EventArgs e) { txtSearch.Text = ""; dataGridView.DataSource = excelData; lblStatus.Text = $"显示全部 {excelData.Rows.Count} 行数据"; } } }
最新发布
09-17
private async void QueryData() { string connectionString = "Server=10.50.32.244;Port=9080;Database=weiwantian_db;Uid=weiwantian;Pwd=weiwantian123...;CharSet=utf8mb4;"; using (MySqlConnection connection = new MySqlConnection(connectionString)) { try { await connection.OpenAsync(); DateTime dateStart = dateTimePicker2.Value.Date; DateTime dateEnd = dateTimePicker3.Value.Date.AddDays(1).AddTicks(-1); // 优化的查询语句 - 移除FORCE INDEX但保留其他优化 string query = @" SELECT b.ID_Card_Number, b.`Name`, a.data, a.chuqing, a.qingjia, a.tiaoxiu, a.jiaban, a.lizhi, a.qingjialeixing, a.qita, a.suoding, a.bumen_lock, a.firstshenpi, a.kezhang_shenpi, a.shenpi_time, a.update_user, a.genxinshenpi, a.genxinshijian, b.14ID, b.`Type`, b.Department, b.Section, b.Workshop, b.Large_Group, b.Team FROM ri_gongshi a INNER JOIN zsg_personnel_list b ON a.ID_Card_Number = b.ID_Card_Number WHERE a.data BETWEEN @DateStart AND @DateEnd AND (@Department IS NULL OR b.Department = @Department) AND (@Section IS NULL OR b.Section = @Section) AND (@Workshop IS NULL OR b.Workshop = @Workshop) AND (@LargeGroup IS NULL OR b.Large_Group = @LargeGroup) AND (@Team IS NULL OR b.Team = @Team) AND (@IDCardNumber IS NULL OR b.ID_Card_Number = @IDCardNumber) AND (@Name IS NULL OR b.Name = @Name) ORDER BY a.data DESC"; using (MySqlCommand command = new MySqlCommand(query, connection)) { // 设置所有参数,空值用DBNull.Value表示 command.Parameters.AddWithValue("@DateStart", dateStart); command.Parameters.AddWithValue("@DateEnd", dateEnd); // 处理可查询参数 command.Parameters.AddWithValue("@Department", string.IsNullOrWhiteSpace(TextBoxBumenR.Text) ? (object)DBNull.Value : TextBoxBumenR.Text.Trim()); command.Parameters.AddWithValue("@Section", string.IsNullOrWhiteSpace(TextBoxKeshiR.Text) ? (object)DBNull.Value : TextBoxKeshiR.Text.Trim()); command.Parameters.AddWithValue("@Workshop", string.IsNullOrWhiteSpace(TextBoxChejianR.Text) ? (object)DBNull.Value : TextBoxChejianR.Text.Trim()); command.Parameters.AddWithValue("@LargeGroup", string.IsNullOrWhiteSpace(TextBoxDazuR.Text) ? (object)DBNull.Value : TextBoxDazuR.Text.Trim()); command.Parameters.AddWithValue("@Team", string.IsNullOrWhiteSpace(TextBoxBanzuR.Text) ? (object)DBNull.Value : TextBoxBanzuR.Text.Trim()); command.Parameters.AddWithValue("@IDCardNumber", string.IsNullOrWhiteSpace(textBoxIDR.Text) ? (object)DBNull.Value : textBoxIDR.Text.Trim()); command.Parameters.AddWithValue("@Name", string.IsNullOrWhiteSpace(textBoxnameR.Text) ? (object)DBNull.Value : textBoxnameR.Text.Trim()); command.CommandTimeout = 120; // 使用异步数据读取 using (MySqlDataReader reader = await command.ExecuteReaderAsync()) { DataTable dataTable = new DataTable(); dataTable.Load(reader); dataGridView2.DataSource = dataTable; // 数据加载完成后应用格式 } } } catch (Exception ex) { MessageBox.Show("数据库查询错误: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Diagnostics.Debug.WriteLine($"数据库查询错误: {ex}"); } } }将进度显示到progressBar1
07-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值