|
-
Apr 2nd, 2011, 03:19 AM
#1
Thread Starter
Addicted Member
[RESOLVED] Add value selected row Datagrid
how to add value to selected row at datagridview control.
hire my code to display and add row at datagrid :
vb.net Code:
Public Class Form2
Dim dt As New DataTable("view")
Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dt.Columns.Add(New DataColumn("Col1"))
dt.Columns.Add(New DataColumn("Col2"))
dg.DataMember = "view"
dg.DataSource = dt
End Sub
'new rows
Private Sub btnAddRow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddRow.Click
Dim dr As DataRow
dr = dt.NewRow
dr.Item(0) = ""
dr.Item(1) = ""
dt.Rows.Add(dr)
End Sub
'add value at selected row
Private Sub addValue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addValue.Click
' ???
End Sub
End Class
thank you
-
Apr 2nd, 2011, 09:39 AM
#2
Re: Add value selected row Datagrid
First up, you shouldn't be setting the DataMember. You would only set the DataMember to the name of a DataTable if you were setting the DataSource using a DataSet containing that DataTable. Your DataTable is the DataSource so there is no DataMember.
As for the question, you should bind your table to the grid via a BindingSource. That way, you can use the Current property of the BindingSource to get a DataRowView for the current row. You then set it's fields by name or index:
vb.net Code:
Me.BindingSource1.DataSource = dt dg.DataSource = Me.BindingSource1
vb.net Code:
Dim row = DirectCast(Me.BindingSource1.Current, DataRowView) row(0) = firstColumnValue row("ColumnName") = namedColumnValue
-
Apr 2nd, 2011, 11:27 PM
#3
Thread Starter
Addicted Member
Re: Add value selected row Datagrid
Thank you code can run with either
But what if the datagrid I is not connected to the database?
-
Apr 2nd, 2011, 11:36 PM
#4
Re: Add value selected row Datagrid
There's no such thing as a control connected to a database. Controls are bound to a list of data. That list might be a DataTable or it might be something else. Even if it's a DataTable, where the data in that table came from is irrelevant to the control. It might be a database or it might not, but a DataTable is a DataTable. If you are binding any list to the grid then do so via a BindingSource and get the current item from the Current property. The type of that object will depend on the type of data you bound in the first place.
For a grid that isn't bound, which would be the exception rather than the rule, you can use the grid's CurrentRow property. That assumes that the control is actually a DataGridView rather than a DataGrid.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|