Solved

Adding a Row to a DataGridView with a string that contains all the parameters

Posted on 2016-09-16
13
33 Views
Last Modified: 2016-09-20
strRowData is a string variable that contains all the parameters for the Add method.  It's value is "22,1,0,1,0,1,1,1", but the statement "DataGridView1.Rows.Add(strRowData)" tries to set the first column to "22,1,0,1,0,1,1,1" rather than the first column to "22", the second column to "1", etc.  How can I run the statement given that one string contains all the parameters?  Is there a way to run dynamic code in vb.net?
0
Comment
Question by:Declan_Basile
  • 8
  • 4
13 Comments
 
LVL 12

Assisted Solution

by:funwithdotnet
funwithdotnet earned 250 total points
ID: 41802465
Create a new row, split the string, add the appropriate value to each column and then add the row.
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 250 total points
ID: 41802562
Hi  Declan_Basile;

You need to use an Object array in order to load a row of data that way. The following code snippet will do that
'' Your data
Dim strRowData = "22,1,0,1,0,1,1,1"
'' Convert your data string into an array
Dim strRowDataArray As Object() = strRowData.Split(New Char() {","c})
'' Add the array as a row in the DataGridView
dataGridView1.Rows.Add(strRowDataArray)

Open in new window

Be aware that adding rows to the DatedGridView in this manner requires that you do NOT have a bound data source to the DatedGridView control. Also you need to make sure that you have added the correct number of columns using code as the following
'' The number of columns in the DataGridView
dataGridView1.ColumnCount = 8
dataGridView1.Columns(x).Name = "Column Name"
'' Where x is the column index"

Open in new window

0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41805441
I already have an array of Long Integers.  In fact, I created strRowData from it, but DataGridView1.Rows.Add(LongIntArray) doesn't work.  It looks like it needs to be an array of objects, not an array of Long Integers.  I've experimented further, and this works:

Dim x(7) As Object        
x(0) = 22
DataGridView1.Rows.Add(x(0), 0)

But this doesn't ...

Dim x(7) As Object        
x(0) = Clng(22)
DataGridView1.Rows.Add(x(0), 0)

How can I convert the array of long integers to an array of objects?
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41805486
Please post all code that you are using to  instantiate the DataGridView and initialize it as well as your code that you are using to load rows of data.
0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41805524
    Private Sub AddDataGridRows()

        Dim cn As New SqlConnection(strConn)
        Dim cmd As New SqlCommand
        Dim rdr As SqlDataReader
        Dim lngUserId As Long
        Dim OpIds((DataGridView1.ColumnCount - 1)) As Long
        Dim Vals((DataGridView1.ColumnCount - 1)) As Long
        Dim i As Integer

        For i = 0 To OpIds.GetUpperBound(0)
            OpIds(i) = DataGridView1.Columns(i).Tag
        Next

        cn.Open()
        cmd.CommandText = "procUserOperations"
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Connection = cn
        cmd.Parameters.Add("@ParentOperationId", SqlDbType.Int)
        cmd.Parameters("@ParentOperationId").Value =
            IIf(IsDBNull(cbxParentOperationId.SelectedValue), "0", cbxParentOperationId.SelectedValue)
        rdr = cmd.ExecuteReader

        DataGridView1.Rows.Clear()
        lngUserId = 0
        Do While rdr.Read
            If rdr("UserId") <> lngUserId Then
                If lngUserId <> 0 Then
                    Vals(0) = lngUserId
                    Call AddDataGridRow(Vals)
                    Array.Clear(OpIds, 0, OpIds.GetUpperBound(0))
                End If
                lngUserId = rdr("UserId")
            End If
            Vals(Array.IndexOf(OpIds, CLng(rdr("OperationId")))) =
                 IIf(rdr("ChildOps") = rdr("UserChildOps"), 2, 1)
        Loop
        If lngUserId <> 0 Then
            Vals(0) = lngUserId
            Call AddDataGridRow(Vals)
        End If

        'DataGridView1(1, 0).Style.BackColor = Color.LightGray
        'DataGridView1(2, 0).Style.BackColor = Color.Yellow

    End Sub

    Private Sub AddDataGridRow(ByRef Vals() As Long)

        'Dim i As Integer
        'Dim strRowData As String

        'strRowData = Vals(0).ToString
        'For i = 1 To Vals.GetUpperBound(0)
        'strRowData = strRowData & IIf(Vals(i) = 0, ", 0", ", -1")
        'Next

        DataGridView1.Rows.Add(Vals)

    End Sub

Open in new window

0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41805685
In order to do this
For i = 0 To OpIds.GetUpperBound(0)
    OpIds(i) = DataGridView1.Columns(i).Tag
Next

Open in new window

You needed to add Columns to the DataGridView. If you created the DataGridView with the Form designer please open the file FormName.Designer.vb and copy the section of code inside the subroutine called Private Sub InitializeComponent() and the section marked as 'DataGridView1. Also post any other code that you have that initialize it such as adding columns. I am trying to build a test project with what you have so I can test the code you are using.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Author Comment

by:Declan_Basile
ID: 41806569
I do have code to add the columns.
   Private Sub RefreshMatrix()

        Dim SQL As String
        Dim cn As New ADODB.Connection()
        cn.ConnectionString = strConn2
        cn.Open()

        SQL = "Select DISTINCT O.OperationId, O.Operation, " &
            "IIf(R2.ParentOperationId Is NULL, 0, 1) As IsParent " &
            "FROM (Operations O INNER JOIN RelOperationOperation R " &
            "On O.OperationId = R.ChildOperationId) LEFT JOIN RelOperationOperation R2 On " &
            "R.ChildOperationId = R2.ParentOperationId WHERE R.ParentOperationId = " &
            IIf(IsDBNull(cbxParentOperationId.SelectedValue), "0", cbxParentOperationId.SelectedValue.ToString) &
            " ORDER BY O.Operation"

        Dim rs As New ADODB.Recordset()
        rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient
        rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
        rs.LockType = ADODB.LockTypeEnum.adLockReadOnly
        rs.Open(SQL, cn)
        rs.ActiveConnection = Nothing
        cn.Close()

        DataGridView1.Columns.Clear()
        AddDataGridCbxColumn()
        rs.MoveFirst()
        Do While Not rs.EOF
            AddDataGridColumn(rs.Fields("OperationId").Value.ToString, rs.Fields("Operation").Value,
                              rs.Fields("IsParent").Value)
            rs.MoveNext()
        Loop
        AddDataGridRows()
        'Dim da As New System.Data.OleDb.OleDbDataAdapter()
        'Dim ds As New DataSet()
        'da.Fill(ds, rs, "products")
        'DataGridView1.Columns.Clear()

    End Sub

Open in new window

0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41806574
I'm going to try adding in a blank row and then assigning the values to the cells.
0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41806612
This code works ...
    Private Sub AddDataGridRow(ByRef Vals() As Long)

        DataGridView1.Rows.Add()
        DataGridView1.Rows(DataGridView1.RowCount - 2).Cells(0).Value = 22
        'Note the header row counts as a row, hence RowCount - 2

    End Sub

This code does not work

    Private Sub AddDataGridRow(ByRef Vals() As Long)

        DataGridView1.Rows.Add()
        DataGridView1.Rows(DataGridView1.RowCount - 2).Cells(0).Value = Vals(0)

    End Sub

Why doesn't the second version work?  I even displayed the value of Vals(0) to confirm the value using the statement "MsgBox(Vals(0))" and it displayed "22".
0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41806664
Note Column(0) of DataGridView1 is a combobox column bound to a datasource and its ValueMember is bound to a column of the datasource that's a long integer.
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41806725
Please do the following. Create a test project with one DataGridView control and use the code that works and does not work from two post back because I am confused on what you're trying to achieve.

Thanks
0
 
LVL 1

Author Comment

by:Declan_Basile
ID: 41807089
I declared the vals array as Int32 instead of Long and it worked!
0
 
LVL 1

Author Closing Comment

by:Declan_Basile
ID: 41807686
Thank you!
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Using MS Code on my Mac 6 45
asp.net mvc5 3 37
Default parameter problem in C# 3 27
Why don't I see this table in EDMX file? 2 20
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now