【问题标题】:How to retrieve data into a datagridview row by row from a SQL Server database using C#如何使用 C# 从 SQL Server 数据库中逐行将数据检索到 datagridview 中
【发布时间】:2021-10-02 16:56:35
【问题描述】:

我正在开发一个 C# Windows 窗体应用程序。我需要从 SQL Server 数据库中将数据检索到 datagridview 中。

我的程序是如何工作的:

  1. 在文本框中输入产品代码
  2. 点击“显示按钮”

然后将与产品代码相关的产品详细信息(名称和价格)加载到 datagridview 的第一行。

当使用另一个代码完成此操作时,我需要将数据加载到下一行。

但问题是通过覆盖现有数据,检索数据仅加载到第一行。没有逐行加载。

如何在通过产品代码搜索数据时将数据放到下一行而不丢失 datagridview 中的现有数据?任何帮助将不胜感激。

Image of my program

这是我当前的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Retrieve_Data_In_Datagridview
{
    public partial class Form1 : Form
    {
        SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=InventoryManagement;Integrated Security=True");

        public Form1()
        {
            InitializeComponent();
        }

        private void bind_data()
        {
            SqlCommand cmd = new SqlCommand("SELECT [product_code], [product_name], [price], [discounted_price] FROM [product_tab] WHERE [product_code] = @parm1", conn);
            cmd.Parameters.AddWithValue("@parm1", textBox1.Text);

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;

            DataTable dt = new DataTable();
            dt.Clear();
            da.Fill(dt);

            dataGridView1.DataSource = dt;
            
            //DataGridView1 navigating to next row
            int nRow;
            nRow = dataGridView1.CurrentCell.RowIndex;

            if (nRow < dataGridView1.RowCount)
            {
                dataGridView1.CurrentCell = dataGridView1.Rows[++nRow].Cells[0];
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bind_data();
        }
    }
}

【问题讨论】:

  • 代码行…dataGridView1.DataSource = dt;…将用dt“替换”现有的网格数据源。如果你想“组合”这两个表,我猜你可以使用DataTable.ImportRow(DataRow) Method 将查询中的所有行导入现有的网格数据源。鉴于此,您似乎需要创建一个“全局”DataTable 以绑定到网格。

标签: c# sql-server datagridview


【解决方案1】:

问题基本上是每次您这样做时:dataGridView1.DataSource = dt; 您将源更改为仅包含上次查询结果的新数据表。 这是您需要的东西: [https://stackoverflow.com/questions/9608647/how-to-add-new-row-to-datagridview]

【讨论】:

    猜你喜欢
    • 2012-12-19
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    相关资源
    最近更新 更多