Solved

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

Posted on 2016-09-16
13
46 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
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
 
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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

805 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