数据表返回空值 [英] Datatable return null values

查看:90
本文介绍了数据表返回空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Guys,我从数据库中选择值,但数据表返回空值



我尝试过:



Hello Guys, i am selecting value from database but datatable return null values

What I have tried:

connection.Open();
            DataSet dsa1 = new DataSet();
            DataTable dt1 = new DataTable();
            dsa1.Tables.Add(dt1);
            OleDbDataAdapter da1 = new OleDbDataAdapter();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                da1 = new OleDbDataAdapter("SELECT [Price] from [Purchase Record] where [Product Name] = '" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "'", connection);
                da1.Fill(dt1);
                dataGridView2.DataSource = dt1;
                connection.Close();
            }

推荐答案

存在逻辑错误。

1.您正在填写一个循环因此,每次填充后,它将擦除以前填充的数据。 (数据被替换而不是附加。)

2.连接在循环中关闭,因此在第一次迭代后,表对象将为空。
There is logical error.
1. You are Filling in a loop so after every fill it will wipe previous filled data. (Data is replaced not appended.)
2. connection is closed in loop so after first iteration the table object will be null.


您的代码被修改。使用这个

这可能适用于你



your code is modified.. use this
this may be work for u

connection.Open();
            DataSet dsa1 = new DataSet();
            DataTable dt1 = new DataTable();
            dsa1.Tables.Add(dt1);
            OleDbDataAdapter da1 = new OleDbDataAdapter();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                da1 = new OleDbDataAdapter("SELECT [Price] from [Purchase Record] where [Product Name] = '" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "'", connection);
                da1.Fill(dt1);
                int y=dataGridView1.Rows.Add();
                dataGridView1.Rows[y].Cells[0].Value=dt1.Rows[0].Field<double>(0);
                dt1.Clear();
                connection.Close();
            }


我不确定我是否理解这种情况,但是......


正如已经指出的那样,不要关闭循环内部的连接,否则第二次获取将失败。此外,如果你经常更换网格的数据源,只显示最后一个,所有其他的提取都是徒劳的。



所以这看起来你正试图以两个阶段填充网格中的数据,首先获取初始数据集,然后尝试获取先前获取的行的价格。



如果这是通常情况下,这些不是作为单独的操作完成的。相反,数据通常在一次调用中获取,并且连接用于同时从两个表中正确地获取数据。看看 SQL连接的可视化表示 [ ^ ]
I'm not sure if I understand the situation correctly, but...

As already pointed out, don't close the connection inside the loop, otherwise the second fetch will fail. Also if you constantly replace the datasource of the grid, only the last one is shown, all other fetches are in vain.

So this looks like you're trying to fill the data in the grid in two phases, first you fetch the initial set of data and the you try fetch prices for the rows previously fetched.

If this is the case, normally these are not done as separate operations. Instead the data is typically fetched in one call and a join is used to correctly fetch data from two tables at the same time. Have a look at Visual Representation of SQL Joins[^]


这篇关于数据表返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆