【发布时间】:2021-10-02 16:56:35
【问题描述】:
我正在开发一个 C# Windows 窗体应用程序。我需要从 SQL Server 数据库中将数据检索到 datagridview 中。
我的程序是如何工作的:
- 在文本框中输入产品代码
- 点击“显示按钮”
然后将与产品代码相关的产品详细信息(名称和价格)加载到 datagridview 的第一行。
当使用另一个代码完成此操作时,我需要将数据加载到下一行。
但问题是通过覆盖现有数据,检索数据仅加载到第一行。没有逐行加载。
如何在通过产品代码搜索数据时将数据放到下一行而不丢失 datagridview 中的现有数据?任何帮助将不胜感激。
这是我当前的代码:
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