Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Finding the value of a cell or a column within a row in a datagrid

Posted on 2004-10-06
5
Medium Priority
?
156 Views
Last Modified: 2010-04-23
I have a program that is a datagrid combobox in VB.Net, I would like to find or put in a textbox each time I go down to the datagrid the value of a cell or column (let's say column 2), how do I do that ?

This is how my program was written.  

Option Strict Off
Option Explicit On

Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Data
Imports System.Data.OleDb
Imports System.Resources
Imports System.Runtime.InteropServices
Imports System.Data.SqlClient


Namespace DataGridTextBoxCombo
 
    '/ <summary>
    '/ Summary description for Form1.
    '/ </summary>
    Public Class Form1
        Inherits System.Windows.Forms.Form

        Protected dsProducts As New DataSet
        Private dataGrid1 As System.Windows.Forms.DataGrid
        Private myDataSet As DataSet
        Private dataAdapter As OleDbDataAdapter

        Protected Const SQL_CONNECTION_STRING As String = _
        "Server=sql;" & _
        "DataBase=Management_Survey;" & _
        "Integrated Security=SSPI"

        Protected Const MSDE_CONNECTION_STRING As String = _
            "Server=(sqltest)\NetSDK;" & _
            "DataBase=Management_Survey;" & _
            "Integrated Security=SSPI"

        '/ <summary>
        '/ Required designer variable.
        '/ </summary>
        Protected Const PRODUCT_TABLE_NAME As String = "tblManager"
        Protected dvProducts As DataView

        Protected Const CAPTION_TITLE As String = "Bind Data to a ComboBox"
        Protected Const DEFAULT_SORT As String = "ManagerName ASC"
        ' Protected Const CAPTION_ICON_BUTTON As MsgBoxStyle = CType(MsgBoxStyle.Information + MsgBoxStyle.OKOnly, MsgBoxStyle)

        Private components As System.ComponentModel.Container = Nothing
        Public Sub New()
            '
            ' Required for Windows Form Designer support
            '
            InitializeComponent()

           
            MakeDataSetAndBindGrid()
        End Sub 'New

        Private Sub MakeDataSetAndBindGrid()
            ' Set the connection and sql strings
            Dim connString As String = "Provider=sqloledb;Data Source = SQL; Initial Catalog = Management_Survey; Integrated Security = SSPI"
            Dim sqlString As String = "SELECT Description, ratingid FROM tblQuestion"

            dataAdapter = Nothing
            myDataSet = Nothing

            Try
                ' Connection object
                Dim connection As New OleDbConnection(connString)

                ' Create data adapter object
                dataAdapter = New OleDbDataAdapter(sqlString, connection)


               
                ' Create a dataset object and fill with data using data adapter's Fill method
                myDataSet = New DataSet
                dataAdapter.Fill(myDataSet, "tblQuestion")


                'now load the datatable for the bound combobox...
                'notice that the combobox & grid are NOT  bound to the same
                'table (if bound to the same table, you must have different binding contexts)
                sqlString = "SELECT ratingdesc, ratingid FROM tblRating order by ratingid"
                dataAdapter = New OleDbDataAdapter(sqlString, connection)
                dataAdapter.Fill(myDataSet, "tblrating")


                sqlString = "SELECT ManagerName, ManagerId FROM tblManager order by managerid"
                dataAdapter = New OleDbDataAdapter(sqlString, connection)
                dataAdapter.Fill(myDataSet, "tblManager")


                connection.Close()
            Catch ex As Exception
                MessageBox.Show(("Problem with access-   connection: " + connString + "            query: " + sqlString + ex.ToString()))
                Me.Close()
                Return
            End Try

            ' Create a table style that will hold the new column style
            ' that we set and also tie it to our customer's table from our DB
            Dim tableStyle As New DataGridTableStyle
            tableStyle.MappingName = "tblquestion"

            Dim dt As DataTable = myDataSet.Tables("tblquestion")

            ' make the dataGrid use our new tablestyle and bind it to our table
            Dim i As Integer

            While i < dt.Columns.Count
                If i <> 1 Then
                    Dim TextCol As New DataGridTextBoxColumn
                    TextCol.MappingName = dt.Columns(i).ColumnName
                    TextCol.HeaderText = dt.Columns(i).ColumnName
                    TextCol.Width = 450
                    tableStyle.GridColumnStyles.Add(TextCol)

                Else
                    Dim ComboTextCol As New DataGridComboBoxColumn
                    ComboTextCol.MappingName = "ratingId" 'must be from the grid table...
                    ComboTextCol.HeaderText = "Rating"
                    ComboTextCol.Width = 120
                    'DataView dv = new DataView(myDataSet.Tables["customerList"], "", "customerID", DataViewRowState.CurrentRows);
                    ComboTextCol.ColumnComboBox.DataSource = myDataSet.Tables("tblrating").DefaultView 'dv;
                    ComboTextCol.ColumnComboBox.DisplayMember = "ratingdesc"
                    ComboTextCol.ColumnComboBox.ValueMember = "ratingID"


                    tableStyle.PreferredRowHeight = ComboTextCol.ColumnComboBox.Height + 2

                    tableStyle.GridColumnStyles.Add(ComboTextCol)

                End If

                i = i + 1

            End While

            dataGrid1.TableStyles.Clear()
            dataGrid1.TableStyles.Add(tableStyle)
            dataGrid1.DataSource = dt


            'make it no append
            myDataSet.Tables("tblquestion").DefaultView.AllowDelete = False
            myDataSet.Tables("tblquestion").DefaultView.AllowNew = False
            myDataSet.Tables("tblquestion").DefaultView.AllowEdit = False

        End Sub 'MakeDataSetAndBindGrid
       

        '/ <summary>
        '/ Clean up any resources being used.
        '/ </summary>
        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 'Dispose
        Friend WithEvents Label1 As System.Windows.Forms.Label
        Friend WithEvents cboRightCombo As System.Windows.Forms.ComboBox
        Friend WithEvents Button1 As System.Windows.Forms.Button
        Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
        Friend WithEvents Button2 As System.Windows.Forms.Button
        Private Sub InitializeComponent()
            Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form1))
            Me.dataGrid1 = New System.Windows.Forms.DataGrid
            Me.Label1 = New System.Windows.Forms.Label
            Me.cboRightCombo = New System.Windows.Forms.ComboBox
            Me.Button1 = New System.Windows.Forms.Button
            Me.TextBox1 = New System.Windows.Forms.TextBox
            Me.Button2 = New System.Windows.Forms.Button
            CType(Me.dataGrid1, System.ComponentModel.ISupportInitialize).BeginInit()
            Me.SuspendLayout()
            '
            'dataGrid1
            '
            Me.dataGrid1.AlternatingBackColor = System.Drawing.Color.Gainsboro
            Me.dataGrid1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                        Or System.Windows.Forms.AnchorStyles.Left) _
                        Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.dataGrid1.BackColor = System.Drawing.Color.Silver
            Me.dataGrid1.BackgroundColor = System.Drawing.Color.Lavender
            Me.dataGrid1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
            Me.dataGrid1.CaptionBackColor = System.Drawing.Color.DarkSlateBlue
            Me.dataGrid1.CaptionFont = New System.Drawing.Font("Tahoma", 8.0!)
            Me.dataGrid1.CaptionForeColor = System.Drawing.Color.White
            Me.dataGrid1.CaptionText = "Rate your Manager/Supervisor"
            Me.dataGrid1.DataMember = ""
            Me.dataGrid1.FlatMode = True
            Me.dataGrid1.ForeColor = System.Drawing.Color.Black
            Me.dataGrid1.GridLineColor = System.Drawing.Color.White
            Me.dataGrid1.HeaderBackColor = System.Drawing.Color.DarkGray
            Me.dataGrid1.HeaderForeColor = System.Drawing.Color.Black
            Me.dataGrid1.LinkColor = System.Drawing.Color.DarkSlateBlue
            Me.dataGrid1.Location = New System.Drawing.Point(16, 40)
            Me.dataGrid1.Name = "dataGrid1"
            Me.dataGrid1.ParentRowsBackColor = System.Drawing.Color.Black
            Me.dataGrid1.ParentRowsForeColor = System.Drawing.Color.White
            Me.dataGrid1.SelectionBackColor = System.Drawing.Color.DarkSlateBlue
            Me.dataGrid1.SelectionForeColor = System.Drawing.Color.White
            Me.dataGrid1.Size = New System.Drawing.Size(688, 536)
            Me.dataGrid1.TabIndex = 0
            '
            'Label1
            '
            Me.Label1.Location = New System.Drawing.Point(176, 88)
            Me.Label1.Name = "Label1"
            Me.Label1.Size = New System.Drawing.Size(112, 16)
            Me.Label1.TabIndex = 1
            '
            'cboRightCombo
            '
            Me.cboRightCombo.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.cboRightCombo.Location = New System.Drawing.Point(16, 8)
            Me.cboRightCombo.Name = "cboRightCombo"
            Me.cboRightCombo.Size = New System.Drawing.Size(222, 24)
            Me.cboRightCombo.TabIndex = 2
            '
            'Button1
            '
            Me.Button1.Location = New System.Drawing.Point(256, 8)
            Me.Button1.Name = "Button1"
            Me.Button1.Size = New System.Drawing.Size(120, 23)
            Me.Button1.TabIndex = 3
            Me.Button1.Text = "Load Manager's List"
            '
            'TextBox1
            '
            Me.TextBox1.Location = New System.Drawing.Point(456, 8)
            Me.TextBox1.Name = "TextBox1"
            Me.TextBox1.TabIndex = 4
            Me.TextBox1.Text = ""
            '
            'Button2
            '
            Me.Button2.Location = New System.Drawing.Point(592, 8)
            Me.Button2.Name = "Button2"
            Me.Button2.TabIndex = 5
            Me.Button2.Text = "Button2"
            '
            'Form1
            '
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(712, 597)
            Me.Controls.Add(Me.Button2)
            Me.Controls.Add(Me.TextBox1)
            Me.Controls.Add(Me.Button1)
            Me.Controls.Add(Me.cboRightCombo)
            Me.Controls.Add(Me.dataGrid1)
            Me.Controls.Add(Me.Label1)
            Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
            Me.Name = "Form1"
            Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
            Me.Text = "Fabcon Management Survey"
            CType(Me.dataGrid1, System.ComponentModel.ISupportInitialize).EndInit()
            Me.ResumeLayout(False)

        End Sub 'InitializeComponent

        <STAThread()> _
          Public Shared Sub Main()
            Application.Run(New Form1)

        End Sub

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            BindtoDataset()
        End Sub
        Private Sub BindToDataSet()
            Try
                LoadData()
                cboRightCombo.DataSource = dvProducts
                cboRightCombo.DisplayMember = "ManagerName"
                cboRightCombo.ValueMember = "ManagerID"

            Catch exp As Exception
                MessageBox.Show(exp.Message, Me.Text)
            End Try
        End Sub
        Private Sub LoadData()
            Dim strConnection As String = SQL_CONNECTION_STRING


            Dim IsConnecting As Boolean = True
            While IsConnecting

                Try

                    Dim northwindConnection As New SqlConnection(strConnection)

                    Dim ProductAdapter As New SqlDataAdapter( _
                        "SELECT * " _
                        & "FROM tblManager", _
                        northwindConnection)

                    ProductAdapter.Fill(dsProducts, PRODUCT_TABLE_NAME)

                    'create the dataview; use a constructor to specify
                    ' the sort, filter criteria for performance purposes
                    dvProducts = New DataView(dsProducts.Tables("tblManager"), "", DEFAULT_SORT, DataViewRowState.OriginalRows)

                    ' Data has been retrieved successfully  
                    ' Signal to break out of the loop by setting isConnecting to false.
                    IsConnecting = False

                    'Handle the situation where a connection attempt has failed
                Catch exc As Exception
                    If strConnection = SQL_CONNECTION_STRING Then
                        ' Couldn't connect to SQL Server.  Now try MSDE.
                        strConnection = MSDE_CONNECTION_STRING

                    Else
                        ' Unable to connect to SQL Server or MSDE


                    End If
                End Try
            End While


        End Sub

     

    End Class 'Form1
End Namespace 'DataGridTextBoxCombo
0
Comment
Question by:FabconIT
5 Comments
 
LVL 19

Expert Comment

by:arif_eqbal
ID: 12245519
Your Question is not clear
What do you want to do locate the cell where user wants to enter values???
If yes then use .CurrentCell

If you mean to say that you would like to show a textbox in the current cell so that user can edit, I think the DataGrid does it automatically for you..
0
 
LVL 7

Accepted Solution

by:
J_Mak earned 1000 total points
ID: 12245618
Have a look at this link:

http://www.syncfusion.com/FAQ/WinForms/FAQ_c44c.asp

Cheers!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

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

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
Loops Section Overview
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses

963 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