Md Nasir Uddin
Md Nasir Uddin

Reputation: 2180

Adding Column Value Dynamically to a DataGridview

I have three column in my datagridview .One is text ,one is Combo and another one is Text ...i don't want to use datasource want to add values on cell like datagridview.Rows[].cells[].value. Help me how i can do it? My database have several columns...How to add column value dynamically....

Upvotes: 0

Views: 762

Answers (3)

Eric
Eric

Reputation: 8078

I just had to do the same exact type of thing...here is how you add a column.

If Not IsPostBack Then <br>

        Dim field As New TemplateField
        field.HeaderText = "Name of Column"
        Dim col As DataControlField = field
        GridView.Columns.Add(col)

        End If

**In the Gridview_rowcreated Sub

e.row.cells(cellnumber from 0 to N).controls.Add(data)

you're going to have to create a connection and a connection string

here is an example...

Dim Dbconn As SqlConnection
Dim Dbcmd As SqlCommand

Dbcmd = New Data.SqlClient.SqlCommand()
Dbcmd.Connection = Dbconn
Dbcmd.CommandType = Data.CommandType.Text

Dbcmd.Commandtext = "select * from table"
dbconn.open()

//then you need a data reader

dim dr as sqlclient.sqldatareader
dr = dbcmd.executereader
while dr.read
add each item to a list
end while

then on page load set your datasource of the grid to the list

hope this helps...if you have any questions just ask me.

Upvotes: 1

AndrewS
AndrewS

Reputation: 3500

Try something along the lines of

dataGrid.Rows.Add(new object[] { "value1", 42, "value3"});

Upvotes: 0

Vikram
Vikram

Reputation: 6877

I would highly recommend to use a Repeater instead of datagridview and render as many columns as you want.

.aspx code

<tr>
    <asp:Repeater ID="rptDayHeaders" runat="server">
        <ItemTemplate>
            <td>
                <strong><asp:Literal ID="ltMonthHeader" runat="server"></asp:Literal></strong>
            </td>
        </ItemTemplate>
    </asp:Repeater>
</tr>

.aspx.vb code

rptDayHeaders.DataSource = daysList
rptDayHeaders.DataBind()

where dayslist needs to be an array of the number of columns you want.

We have used the same approach to generate a complete Gantt Chart

Upvotes: 0

Related Questions