如何将新列添加到datagridview控件? [英] How to add a new column to a datagridview control ?

查看:99
本文介绍了如何将新列添加到datagridview控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有DataSource的DataGridView来自文本文件



I have a DataGridView with DataSource from a text file

Command     Article      Qte       PU
abcd        ab17        17        1.8





现在我需要从数据库添加另一列,我有很多问题。

虽然添加它自动显示在第一列下,我想将它添加为新列我将使用sql requet将第二列与数据库进行比较并填充列我想要的,将是这样的





Now I need to add another column from a database and I have a lot of problem with it.
While adding it show under the first column automatically and what I want to add it as new column i will make a sql requet to compare second column with database and fill the column what i want,will be like this

Command     Article     Qte       PU          Designation
abcd        ab17        17        1.8         AAAAAAAA





我尝试过:





What I have tried:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

      Dim ouvrir As New OpenFileDialog
      If ouvrir.ShowDialog = DialogResult.OK Then

          Dim sr As New StreamReader(ouvrir.FileName)
          While Not sr.EndOfStream
              DataGridView1.Rows.Add(sr.ReadLine.Split(CChar(vbTab)))
          End While
      End If
  End Sub

  Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
      Dim cmd As New SqlCommand("select Numero from DetailReceptionFrs", cn)
      Dim da As New SqlDataAdapter(cmd)
      Dim dt As New DataTable
      da.Fill(dt)
      DataGridView1.DataSource = dt

  End Sub

推荐答案

当你设置DataSource时,它提供了DGV的架构 - 这意味着你不应该只是添加一列到DGV本身。

你可以,只需将其添加到DGV.Columns集合中:

When you set the DataSource, that provides the schema for the DGV - and that means you shouldn't just "add a column" to the DGV itself.
You can, just by adding it to the DGV.Columns collection:
DataGridView1.Columns.Add("NameOfColumn", "Coulumn Heading Text")

但是如果你添加行并尝试保存它/稍后更新源,这可能会导致问题。

您也可以通过将它添加到基础DataTable来实现:

But that may cause problems if you add rows and try to save it / update the source later.
You can also do it by addit it to the underlying DataTable:

Dim dt As DataTable = TryCast(DataGridView1.DataSource, DataTable)
dt.Columns.Add("Rating")

哪个可能效果更好。


请先阅读我对该问题的评论。



您的代码有几个问题。好吧......



此代码:

Please, read my comment to the question first.

There's several issues with your code. Well...

This code:
DataGridView1.Rows.Add(sr.ReadLine.Split(CChar(vbTab)))



向datagridview组件添加行。

这一个:


adds rows to the datagridview component.
And this one:

DataGridView1.DataSource = dt



删除以前的数据并使用datatable绑定数据。



您必须决定使用哪种方法来显示数据:a)未绑定或b)绑定DataGridView。

Ad a)

您可以手动逐行添加数据。您可以在 Button1_Click 事件中执行此操作。

有关详细信息,请参阅:演练:创建未绑定的Windows窗体DataGridView控件Microsoft Docs [ ^ ]



广告b)

您创建数据源并且将它与DataGridView组件绑定。你可以在 Button2_Click 事件中这样做。

更多:如何:将数据绑定到Windows窗体DataGridView控件Microsoft Docs [ ^ ]

如何:在数据绑定的Windows窗体DataGridView控件中自动生成列Microsoft Docs [ ^ ]








removes previous data and binds data with datatable.

You have to decide what method you want to use to display data: a) unbound or b) bound DataGridView.
Ad a)
You adds data manually, row by row. You do that in Button1_Click event.
For further details, please see: Walkthrough: Creating an Unbound Windows Forms DataGridView Control | Microsoft Docs[^]

Ad b)
You make a datasource and bind it with DataGridView component. You do that in Button2_Click event.
More: How to: Bind data to the Windows Forms DataGridView control | Microsoft Docs[^]
How to: Autogenerate Columns in a Data-Bound Windows Forms DataGridView Control | Microsoft Docs[^]



Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

      Using ouvrir As New OpenFileDialog
          If ouvrir.ShowDialog = DialogResult.OK Then BindData(ouvrir.FileName)
      End Using
End Sub





非linq解决方案:



Non-linq solution:

Private Sub BindData(sFileName As String)

	'create a datatable object to bind data to DataGridView component
Dim dt As DataTable = New DataTable()
	'add columns 
	dt.Columns.AddRange(New DataColumn() _
		{
			New DataColumn("Command", Type.GetType("System.String")), _
			New DataColumn("Article", Type.GetType("System.String")), _
			New DataColumn("Qte", Type.GetType("System.String")), _
			New DataColumn("PU", Type.GetType("System.String")), _
			New DataColumn("Designation", Type.GetType("System.String")) _
		})
	'add data from file
	Using sr As New StreamReader(sFileName)
		While Not sr.EndOfStream
			dt.Rows.Add(sr.ReadLine.Split(New String(){vbTab}, StringSplitOptions.RemoveEmptyEntries))
		End While
	End Using
	'bind data
	With DataGridView1
		.AutoGenerateColumns = True
		.DataSource = dt
	End With
End Sub





Linq解决方案:



Linq solution:

Private Sub BindData(sFileName As String)

	Dim lines As String() = File.ReadAllLines(sFileName)
	'create a datatable object to bind data to DataGridView component
Dim dt As DataTable = New DataTable()
	'add columns 
	dt.Columns.AddRange(New DataColumn() _
		{
			New DataColumn("Command", Type.GetType("System.String")), _
			New DataColumn("Article", Type.GetType("System.String")), _
			New DataColumn("Qte", Type.GetType("System.String")), _
			New DataColumn("PU", Type.GetType("System.String")), _
			New DataColumn("Designation", Type.GetType("System.String")) _
		})
	'add data from file
	dt = lines _
		.Select(Function(x) dt.LoadDataRow(x.Split(New String(){vbTab}, StringSplitOptions.RemoveEmptyEntries), False)) _
		.CopyToDataTable()
	'bind data
	With DataGridView1
		.AutoGenerateColumns = True
		.DataSource = dt
	End With
End Sub







注意#1:我不知道来自Sql Server的数据如何与来自文本文件的数据相关,所以 - 你必须使用你的填写指定列的逻辑。



注意#2:上面的代码不是最优的,但它应该是为您提供如何实现目标的方法。



注意#3:我强烈建议使用使用Statement(Visual Basic)| Microsoft Docs [ ^ ]。请阅读相关文章,找出原因...



祝你好运!




Note #1: i have no idea how the data from Sql Server are related to the data from text file, so - you have to use your logic to fill-in Designation column.

Note #2: above code is not optimal, but it should provide you a way how to achieve your goal.

Note #3: i'd strongly recommend to use Using Statement (Visual Basic) | Microsoft Docs[^]. Please, read related article to find out why...

Good luck!


感谢您的帮助

i已经尝试了昨天它可以工作但它确实填满了我的目标

它显示数据但是在文本文件的最后一行之后而不是从第一行开始


thanks for help
i have tried yesterday and it work however it does fill my goal
it show the data but after last rows from textfile and not from first row

dt.Columns.Add("Command")
       dt.Columns.Add("Article")
       dt.Columns.Add("Qte")
       dt.Columns.Add("PU")

       Dim ouvrir As New OpenFileDialog
       If ouvrir.ShowDialog = DialogResult.OK Then
           Dim sr As New StreamReader(ouvrir.FileName)
           While Not sr.EndOfStream
               dt.Rows.Add(sr.ReadLine.Split(CChar(vbTab)))
           End While
           Using cmd As New SqlCommand("select Designation from DetailReceptionFrs", cn)
               Dim da As SqlDataReader = cmd.ExecuteReader

               dt.Columns.Add("Designation")
               While da.Read
                   Dim newRows As DataRow = dt.NewRow
                   newRows("Designation") = da("Designation")
                   dt.Rows.Add(newRows)
               End While
           End Using

           DataGridView1.DataSource = dt
       End If


这篇关于如何将新列添加到datagridview控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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