Like the title says, I have about 10-15 rows in a local dataset. I need to take any one row, and make it the "default" (on a button click), meaning to take that row and stick it right at the top so it comes up first.

I've been up and down the web for a few days looking at ideas, but I can't get around this one. Do I create a new row at the top, then have it copy the info over, then delete the old row, or is there a cleaner way of doing it? Does anyone have a code snippet they'd like to share?

Thanks in advance!

Recommended Answers

All 4 Replies

Try this code:

Private table As DataTable
Public Sub New()

	table = New DataTable("myTable")
	table.Columns.Add("column 1", GetType(String))
	table.Columns.Add("column 2", GetType(String))
	table.Rows.Add("a1", "b1")
	table.Rows.Add("a2", "b2")
	table.Rows.Add("a3", "b3")
	table.Rows.Add("a4", "b4")
	dataGridView1.DataSource = New BindingSource(table, Nothing)
End Sub

Private Sub button1_Click(sender As Object, e As EventArgs)
	Dim selectedRow As DataRow = table.Rows(dataGridView1.CurrentRow.Index)
	Dim newRow As DataRow = table.NewRow()
	newRow.ItemArray = selectedRow.ItemArray
	' copy data
	table.Rows.InsertAt(newRow, 0)
End Sub

as you can see the dataTable is bound to datagridview, so you can see the actual results, when selecting a row and pressing a button. The selected row will move to the top of DGV (the same as in dataTable).
If you want to use the code in dataSet, just create is, and add a dataTable to it.

commented: Thanks for your help and time! Good code! +2

Good snippet- thanks for that

Quick question- I'm a bit stuck on something-

I have this-

table = New DataTable("OfficerInformation")
        table.Columns.Add("Officer", GetType(String))
        table.Columns.Add("Agency", GetType(String))
        table.Columns.Add("Supervisor", GetType(String))

I'm confused on this part-

table.Rows.Add("a1", "b1")
	table.Rows.Add("a2", "b2")

Those values- what are they? I have 15 columns in a single row, with what could be tens of rows.

Mitja Bonca was adding records to the datatable with this part of code, same as with the columns.
If you have the data in a dataset, you don't need to add them manually to your datatable.

Ahhh, gotcha. I was wondering about that also. Thanks for the code, I'm working on it now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.