Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

datagrid update

Status
Not open for further replies.

sladd

IS-IT--Management
Mar 7, 2001
44
US
I'm trying to build a datagrid which lets you update multiple rows at once. I'm able to display my data in the grid and, using templates, allow the user to edit the data in the grid. I'm lost on how I access the data in the grid afterwards. To test, I am simply trying to loop through the datagrid and output a field to a variable. If I'm able to get this data to the variable then I'm confident I can get it back into the database.

My code below is a test program. I have a table with a location code and store description in each row. First I display the data and then let the user change the descriptions. Following, the user clicks a button and I'm hoping to capture the last cell in the grid.

Any help you can provide is greatly appreciated - deadline is only a week away.

Thanks,
Steve

<%@ Page Language=&quot;VB&quot; %>
<script runat=&quot;server&quot;>

' Insert page code here
'

sub bind()
Datagrid1.DataSource = Select_dsstores()
datagrid1.DataBind()
end sub



Function select_dsstores() As System.Data.DataSet
Dim connectionString As String = &quot;Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=d:\2004 Orders.&quot;& _
&quot;mdb&quot;
Dim dbConnection As System.Data.IDbConnection = New System.Data.OleDb.OleDbConnection(connectionString)

Dim queryString As String = &quot;SELECT [travisstores].[ST_KEY], [travisstores].[ST_DESC] FROM [travisstores]&quot;
Dim dbCommand As System.Data.IDbCommand = New System.Data.OleDb.OleDbCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dataAdapter As System.Data.IDbDataAdapter = New System.Data.OleDb.OleDbDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As System.Data.DataSet = New System.Data.DataSet
dataAdapter.Fill(dataSet)

Return dataSet
End Function


'this is where I get lost. I'm trying to figure out how to take the data
'from the datagrid and put it anywhere else. Obviously my final goal is to update
'back to the database but for now I would be happy getting the last row's edits
'into a variable
Function updatecity()
Dim di As datagriditem
dim dr as system.data.datarow
Dim strSQL As String
dim city as string

For Each dr In datagrid1.tables(0).rows
city = CType(dr.FindControl(&quot;st_desc&quot;), TextBox).Text
next
label1.text= &quot;new city: &quot; & city
end function


Sub Button1_Click(sender As Object, e As EventArgs)
updatecity()
End Sub

Sub Button2_Click(sender As Object, e As EventArgs)
bind()
End Sub



End Sub

</script>
<html>
<head>
</head>
<body>
<form id=&quot;Form1&quot; method=&quot;post&quot; runat=&quot;server&quot;>
<asp:DataGrid id=&quot;DataGrid1&quot; runat=&quot;server&quot; AutoGenerateColumns=&quot;False&quot; Datakeyfield=&quot;st_key&quot;>
<Columns>
<asp:TemplateColumn SortExpression=&quot;Locn&quot; HeaderText=&quot;Locn&quot;>
<ItemTemplate>
<asp:TextBox id=&quot;Locn&quot; runat=&quot;server&quot; Width=&quot;109px&quot; Text='<%# DataBinder.Eval(Container, &quot;DataItem.st_key&quot;) %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn SortExpression=&quot;City&quot; HeaderText=&quot;City&quot;>
<ItemTemplate>
<asp:TextBox id=&quot;City&quot; runat=&quot;server&quot; Width=&quot;109px&quot; Text='<%# DataBinder.Eval(Container, &quot;DataItem.st_Desc&quot;) %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle horizontalalign=&quot;Center&quot; forecolor=&quot;DarkSlateBlue&quot; backcolor=&quot;PaleGoldenrod&quot;></PagerStyle>
</asp:DataGrid>
<p>
<asp:Label id=&quot;Label1&quot; runat=&quot;server&quot;>Label</asp:Label>
</p>
<p>
<asp:Button id=&quot;Button1&quot; onclick=&quot;Button1_Click&quot; runat=&quot;server&quot; Text=&quot;check&quot;></asp:Button>
<br />
<asp:Button id=&quot;Button2&quot; onclick=&quot;Button2_Click&quot; runat=&quot;server&quot; Text=&quot;Bind&quot;></asp:Button>
</p>
</form>
</body>
</html>
 
Hi Sladd,

I tried it today, but in VB.Net only.
The user is able to update the data in the DB(SQL Server)
just through the grid. Hope it'll help you. You'll see my code. The Excel Option is only for users who still prefers an Excel Format:

Imports System.Data.SqlClient
Public Class Form1
Inherits System.Windows.Forms.Form

Private Const SELECT_STRING As String = _
&quot;SELECT * FROM tblExcel&quot;
Private Const CONNECT_STRING As String = _
&quot;data source=MPR23;initial catalog=NSRCG;integrated security=SSPI;persist security&quot; & _
&quot; info=False;workstation id=NJ1-1183;packet size=4096&quot;
Dim m_DataSet As DataSet
#Region &quot; Windows Form Designer generated code &quot;

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents btnUpdate As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.dgExcel = New System.Windows.Forms.DataGrid()
Me.DataGridTableStyle1 = New System.Windows.Forms.DataGridTableStyle()
Me.DataGridTableStyle2 = New System.Windows.Forms.DataGridTableStyle()
Me.DataGridTextBoxColumn1 = New System.Windows.Forms.DataGridTextBoxColumn()
Me.btnUpdate = New System.Windows.Forms.Button()
Me.btnExcel = New System.Windows.Forms.Button()
CType(Me.dgExcel, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'dgExcel
'
Me.dgExcel.DataMember = &quot;&quot;
Me.dgExcel.HeaderForeColor = System.Drawing.SystemColors.ControlText
Me.dgExcel.Location = New System.Drawing.Point(16, 24)
Me.dgExcel.Name = &quot;dgExcel&quot;
Me.dgExcel.Size = New System.Drawing.Size(400, 304)
Me.dgExcel.TabIndex = 0
Me.dgExcel.TableStyles.AddRange(New System.Windows.Forms.DataGridTableStyle() {Me.DataGridTableStyle1, Me.DataGridTableStyle2})
'
'DataGridTableStyle1
'
Me.DataGridTableStyle1.AlternatingBackColor = System.Drawing.SystemColors.InactiveCaptionText
Me.DataGridTableStyle1.DataGrid = Me.dgExcel
Me.DataGridTableStyle1.HeaderFont = New System.Drawing.Font(&quot;Microsoft Sans Serif&quot;, 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.DataGridTableStyle1.HeaderForeColor = System.Drawing.SystemColors.ControlText
Me.DataGridTableStyle1.MappingName = &quot;&quot;
'
'DataGridTableStyle2
'
Me.DataGridTableStyle2.AlternatingBackColor = System.Drawing.SystemColors.InactiveCaptionText
Me.DataGridTableStyle2.DataGrid = Me.dgExcel
Me.DataGridTableStyle2.GridColumnStyles.AddRange(New System.Windows.Forms.DataGridColumnStyle() {Me.DataGridTextBoxColumn1})
Me.DataGridTableStyle2.HeaderFont = New System.Drawing.Font(&quot;Microsoft Sans Serif&quot;, 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.DataGridTableStyle2.HeaderForeColor = System.Drawing.SystemColors.ControlText
Me.DataGridTableStyle2.MappingName = &quot;&quot;
'
'DataGridTextBoxColumn1
'
Me.DataGridTextBoxColumn1.Format = &quot;&quot;
Me.DataGridTextBoxColumn1.FormatInfo = Nothing
Me.DataGridTextBoxColumn1.MappingName = &quot;&quot;
Me.DataGridTextBoxColumn1.Width = 75
'
'btnUpdate
'
Me.btnUpdate.Location = New System.Drawing.Point(432, 24)
Me.btnUpdate.Name = &quot;btnUpdate&quot;
Me.btnUpdate.Size = New System.Drawing.Size(80, 32)
Me.btnUpdate.TabIndex = 1
Me.btnUpdate.Text = &quot;Update&quot;
'
'btnExcel
'
Me.btnExcel.Location = New System.Drawing.Point(432, 80)
Me.btnExcel.Name = &quot;btnExcel&quot;
Me.btnExcel.Size = New System.Drawing.Size(80, 32)
Me.btnExcel.TabIndex = 2
Me.btnExcel.Text = &quot;Excel Report&quot;
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(520, 381)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnExcel, Me.btnUpdate, Me.dgExcel})
Me.Name = &quot;Form1&quot;
Me.Text = &quot;Form1&quot;
CType(Me.dgExcel, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)

End Sub

#End Region

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim data_adapter As SqlDataAdapter
'Dim m_DataSet As DataSet

' Create the SqlDataAdapter.
data_adapter = New SqlDataAdapter(SELECT_STRING, _
CONNECT_STRING)

' Map Table to Contacts.
data_adapter.TableMappings.Add(&quot;Table&quot;, &quot;tblExcel&quot;)

' Fill the DataSet.
m_DataSet = New DataSet()
data_adapter.Fill(m_DataSet)

' Bind the DataGrid control to the Contacts DataTable.
dgExcel.DataSource = m_DataSet.Tables(&quot;tblExcel&quot;)

End Sub

'' Save any changes to the data and close the form.
'Private Sub Form1_Closing(ByVal sender As Object, ByVal e _
' As System.ComponentModel.CancelEventArgs) Handles _
' MyBase.Closing
' If m_DataSet.HasChanges() Then
' Dim data_adapter As SqlDataAdapter
' Dim command_builder As SqlCommandBuilder

' ' Create the DataAdapter.
' data_adapter = New SqlDataAdapter(SELECT_STRING, _
' CONNECT_STRING)

' ' Map Table to Contacts.
' data_adapter.TableMappings.Add(&quot;Table&quot;, &quot;tblExcel&quot;)

' ' Make the CommandBuilder generate the
' ' insert, update, and delete commands.
' command_builder = New _
' SqlCommandBuilder(data_adapter)
' ' Save the changes.
' data_adapter.Update(m_DataSet)
' End If
'End Sub

Friend WithEvents DataGridTableStyle1 As System.Windows.Forms.DataGridTableStyle
Friend WithEvents dgExcel As System.Windows.Forms.DataGrid

Private Sub dgExcel_Navigate(ByVal sender As System.Object, ByVal ne As System.Windows.Forms.NavigateEventArgs) Handles dgExcel.Navigate

End Sub
Friend WithEvents DataGridTextBoxColumn1 As System.Windows.Forms.DataGridTextBoxColumn
Friend WithEvents DataGridTableStyle2 As System.Windows.Forms.DataGridTableStyle

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
If m_DataSet.HasChanges() Then
Dim data_adapter As SqlDataAdapter
Dim command_builder As SqlCommandBuilder

' Create the DataAdapter.
data_adapter = New SqlDataAdapter(SELECT_STRING, _
CONNECT_STRING)

' Map Table to Contacts.
data_adapter.TableMappings.Add(&quot;Table&quot;, &quot;tblExcel&quot;)

' Make the CommandBuilder generate the
' insert, update, and delete commands.
command_builder = New _
SqlCommandBuilder(data_adapter)
' Uncomment this code to see the INSERT,
' UPDATE, and DELETE commands.
' Debug.WriteLine(&quot;*** INSERT ***&quot;)
' Debug.WriteLine(command_builder.GetInsertCommand.CommandText)
'Debug.WriteLine(&quot;*** UPDATE ***&quot;)
'Debug.WriteLine(command_builder.GetUpdateCommand.CommandText)
'Debug.WriteLine(&quot;*** DELETE ***&quot;)
'Debug.WriteLine(command_builder.GetDeleteCommand.CommandText)


' Save the changes.
data_adapter.Update(m_DataSet)
End If
End Sub
Friend WithEvents btnExcel As System.Windows.Forms.Button

'To create an Excel Report with an ability to print
Private Sub CreateExcel()
Dim excel As New Excel.ApplicationClass()
Dim rowIndex As Integer = 1
Dim colIndex As Integer = 0
Dim TodayDate As DateTime
'Creating Excel Worksheet
Dim WSheet As New Excel.Worksheet()

TodayDate = Now()

'Adding new worksheet to excel workbooks
WSheet = excel.Application.Workbooks.Add.Worksheets.Add ' CType(excel.Application.Workbooks.Add.Worksheets.Add, Excel.Worksheet)
'excel.Application.Workbooks.Add(True)
'Writing values in Work Sheet
With WSheet

Dim table As DataTable = GetData()

Dim col As DataColumn
For Each col In table.Columns
colIndex += 1
.Cells(1, colIndex) = col.ColumnName
Next col

Dim row As DataRow
For Each row In table.Rows
rowIndex += 1
colIndex = 0
Dim col1 As DataColumn
For Each col1 In table.Columns
colIndex += 1
.Cells(rowIndex, colIndex) = row(col1.ColumnName).ToString()
Next col1
Next row
End With

excel.Visible = True
End Sub

'Call the Excel Report _onClick
Private Sub btnExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExcel.Click
CreateExcel()
End Sub

'Get Data for an Excel Document
Private Function GetData() As System.Data.DataTable
'Dim conn As SqlConnection
'Dim strConn As String
''Set the Conn String to the NSRCG DB
''Don't forget to add TRUSTED_CONNECTION = TRUE for Development
'strConn = &quot;server=MPR23;database=NSRCG;TRUSTED_CONNECTION=TRUE&quot;
'conn = New SqlConnection(strConn)

'Dim adapter As New SqlDataAdapter(&quot;select * FROM tlkpStatus&quot;, conn)


Dim adapter As New SqlDataAdapter(&quot;select * FROM tblExcel&quot;, CONNECT_STRING)
Dim myDataSet As New DataSet()
Try
adapter.Fill(myDataSet, &quot;Status&quot;)
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try

Return myDataSet.Tables(0)
End Function
'End of the GetData
End Class
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top