更新具有绑定源的组合框的datagridview [英] Update a datagridview having combobox with bindingsource

查看:182
本文介绍了更新具有绑定源的组合框的datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Vb.Net从sql server数据库加载数据。我有汽车数据表如下:

I am using Vb.Net to load data from sql server database. I have the car datatable as follows:

我加载汽车详细信息和不同的模型值如下:

I load car details and distinct model values as follows:

sql = " select * from car"
daCar = New SqlDataAdapter(sql, sqlConn)
daCar.Fill(dsDataset, "car")

sql = " select distinct model from car"
daCar = New SqlDataAdapter(sql, sqlConn)
daCar.Fill(dsDataset, "model")

现在,当我加载表单时,我有两个绑定资源,并有一个组合框显示模型的不同值,以便用户自动修改数据很容易

Now when I load the form I have two bindingsources and have one combobox to display the distinct values of the model so user car modify data easily

bsCar = New BindingSource(dsDataset, "car")
bsModel = New BindingSource(dsDataset, "model")
dgvCars.DataSource = bsCar

Dim col2 As New DataGridViewComboBoxColumn
col2.HeaderText = "Model"
col2.Name = "model"

col2.DataSource = bsModel
col2.DisplayMember = "model"
col2.ValueMember = "model"
col2.DataPropertyName = "model"

col2.FlatStyle = FlatStyle.Flat
dgvCars.Columns.Insert(2, col2)
dgvCars.Columns(2).Width = 150

还可以修改combobx的内容我有以下事件:

And also to be able to modify the contents of the combobx I have the following event:

Private Sub dgvCars_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) _
        Handles dgvCars.EditingControlShowing
        If dgvCars.CurrentCell.ColumnIndex = 2
            Dim comboBox As ComboBox = TryCast(e.Control, ComboBox)
            comboBox.DropDownStyle = ComboBoxStyle.DropDown
        End If
    End Sub

除了一个问题:
每当我尝试对dgvCar中的模型组合框进行更改时,失去焦点后,更改将返回到旧的模型。
另外我不能添加新的记录到datagridview!
我如何解决这个问题?

Now every thing works perfect Except one problem: Whenever I try to make changes to the model combobox in the dgvCar, changes will return back to the old ones after losing focus! Also I cant add new records to the datagridview! How can I solve this problem?

推荐答案

从看起来,问题是,你不让数据库知道数据已经改变了。

From the looks of it the problem is, you are not letting the database know the data has changed.

所以当你改变或添加到组合框的东西,它只会添加到组合框(CB),当你刷新CB(当它失去焦点),并得到来自数据库的数据,输入的数据不在数据库中,因此不会显示(丢失)

So when you change or add something to the combo box it only adds to the combo box (CB) and when you refresh the CB (when it loses focus) and get the data from the database, the entered data is not in the database and is therefore not displayed (lost)

要解决此问题,请将SQL查询添加到更新或插入到数据库/表,当您在组合框中添加或更改数据

To solve this add an SQL query to Update or Insert into the database/table when you add or change data in the combo box

还要向数据网格视图添加行,请调查以下代码:

Also to add rows to a data grid view, investigate the following code:

dgvCars.Rows.Add()

这篇关于更新具有绑定源的组合框的datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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