Solved

Windows forms DataGrid  adding items

Posted on 2004-04-12
37
1,209 Views
Last Modified: 2007-12-19
Application Type: Windows form .NET application
Control : DATAGRID

I have 2 Textboxes where we enter first serial Number and lastSerial Number and there exists a Button1 . When button1 is clicked the entry should be added to the datagrid with columns(firstserial) (lastserial) and their respective values. Values can be entered any number of times and button1 being clicked and finally when BUTTON2 is clicked it should be inserted into table

How can i add values to the datagrid and finally how can i collect all the values entered (first serial -- lastserial) to insert into Database?
0
Comment
Question by:sainavya1215
  • 22
  • 14
37 Comments
 
LVL 9

Expert Comment

by:glsac
ID: 10805825
use a DataSet? Is this what you want to know?
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10805969
   Private Sub btnAddRow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddRow.Click
        ' Populate the table.
        Dim BatchData(2) As Object

        BatchData(0) = FirstSerialNumber.Text
        BatchData(1) = SecondSerialNumber.Text
        dtBatch.Rows.Add(BatchData)
        ' Accept the data.
        dsBatch.AcceptChanges()

        ' Attach the DataGrids to the DataTables.
        dgBatch.DataSource = dtBatch
    End Sub

0
 

Author Comment

by:sainavya1215
ID: 10806042
I am currently tryiing this code... could u pls post the code for  dtbatch and dsbatch ........(dgbatch is datagrid what i had understood) it would be helpful for me
0
 

Author Comment

by:sainavya1215
ID: 10806086
I would be using a stored procedure to insert into table ..just wanted to let u know so that the code posted would work
0
 

Author Comment

by:sainavya1215
ID: 10806205
my stored procedure is like this

create procedure sp_ListmissingArticles
@serial_Number1 int,
@serial_number2 int
@id int
begin
         while @serial_number1 <= @serial_number2
                update Table Set  status = 'Missing' where serial_number = @serial_number1  and ID = @id
             @serial_number1 = @Serial_number1 + 1
           end  -- while
 if @@error!=0
             begin
                      return -1000
             end
                      else
                              begin
                                       return -2000
                             end
end
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10806437
The code is irrelevan. You somehow filled ds and datagrid. Now you want to add a row to the dg from 2 text boxes.
This code will write to the dataset and then update grid and dataset
0
 

Author Comment

by:sainavya1215
ID: 10806497
AS I SAID there are 2 cases

1) when button1 is pressed it adds entries to datagrid(Database action insertion doesnot exist)

2) when button2 is pressed all the values lets say : we have 2 entries (Should be entered into db table)

Serial Number   end serial
 20                    30   ( All these values should be updated in the database table using stored proc which is shown above)
 31                    34     ""

So all these are missing articles serial numbers which already exist in a table .. so they have to be updated with status as Missing thats what is shown in stored procedure.

Sorry if i was not clear .. Hope its clear now ?
0
 

Author Comment

by:sainavya1215
ID: 10807360
hi iboutchkine,
was it clear. It would be greatly appreciated if you could help me out regarding this though
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10807481
I still don't see where is your problem. The code I gave you above will enter data from Textboxes to  datagrid (which was your original question).
I think we are clear here.

Now, what is the problem to enter these data to database?

You can use dataadapter update method (only in this case do it before   dsBatch.AcceptChanges()) or plenty different other ways.

PLease clarify.
0
 

Author Comment

by:sainavya1215
ID: 10807634
I am bit confused how to integrate my stored procedure into ur code ........could it be integrated .......pls it would be v helpful

0
 

Author Comment

by:sainavya1215
ID: 10807826
2) when button2 is pressed all the values lets say : we have 2 entries (Should be entered into db table)

Serial Number   end serial
 20                    30   ( All these values should be updated in the database table using stored proc which is shown above)
 31                    34     ""

the reason i asked u about integration of stored proc with ur code is because  It has pull out the values from the Datagrid and update the database

for eg: in the above   20   30 serial numbers it has to update all the serial numbers from 20,21,22 - 30

So I am totally lost how to integrate the stored proc i created with ur code above
0
 

Author Comment

by:sainavya1215
ID: 10807897
Moreover in ur 1st posted code where are dsbatch and dtbatch declared and what exactly are they? this would complete as u said populating the entries into grid
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10807900
Is this what you are looking for?

Dim PubsConn As SqlConnection = New SqlConnection _
    ("Data Source=server;integrated security=sspi;" _
    & "initial Catalog=pubs;")

Dim testCMD As SqlCommand = New SqlCommand _
    ("TestProcedure3", PubsConn)

testCMD.CommandType = CommandType.StoredProcedure

Dim auIDIN As SqlParameter = testCMD.Parameters.Add _
    ("@au_idIN", SqlDbType.VarChar, 11)
auIDIN.Direction = ParameterDirection.Input
Dim auFname As SqlParameter = testCMD.Parameters.Add _
    ("@au_fnam", SqlDbType.VarChar, 30)
auFname.Direction = ParameterDirection.Input

auIDIN.Value = "213-46-8915"
auFname.Value = "Marjorie"
PubsConn.Open()

Dim rvRows As Integer = testCMD.ExecuteNonQuery

Change parameters to yours and try this
0
 

Author Comment

by:sainavya1215
ID: 10807966
Coming to ur 1st posting i get an error

n unhandled exception of type 'System.ArgumentException' occurred in system.data.dll

Additional information: Input array is longer than the number of columns in this table.

for this code:
    ' Populate the table.
        Dim dtbatch As New DataTable()
        Dim dsbatch As New DataSet()

        Dim BatchData(2) As Object

        BatchData(0) = TextBox1.Text.Trim
        BatchData(1) = TextBox2.Text.Trim
        dtBatch.Rows.Add(BatchData)
        ' Accept the data.
        dsBatch.AcceptChanges()

        ' Attach the DataGrids to the DataTables.
        DataGrid1.DataSource = dtbatch

    End Sub
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10807970
>>dsbatch and dtbatch declared and what exactly are they?
dsBatch is dataset
dtBatch is datatable
dgbatch is datagrid

You can declare them anywhere you want. In the procedure, On a form level or in the module
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10807983
Change this line
  Dim BatchData(2) As Object
 

to


  Dim BatchData(1) As Object



0
 

Author Comment

by:sainavya1215
ID: 10808017
same prob exists i tried that too
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10808052
How many columns do you have in your datagrid. The dimension if htebatchData array must be the same

if you have 2 columns
 Dim BatchData(1) As Object
BatchData(0) = FirstSerialNumber.Text
BatchData(1) = SecondSerialNumber.Text

if you have 3 columns
 Dim BatchData(2) As Object
BatchData(0) = FirstSerialNumber.Text
BatchData(1) = SecondSerialNumber.Text
BatchData(2) = some text

etc
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:sainavya1215
ID: 10808117
When u drag a grid onto windows form i cant find any columns where i can set  either in design or in properties? is there a place to check this out or something
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10808168
Datagrid will have so many columns how many fields in your datatable.
For example if you bind it to dataset which wa created from the table  T1, which has 5 fields and you are writing SQL
sSQL= "select * from T1"

and then using dataadapter to fill dataset your bound datagrid wil;l have 5 columns

if you are using

sSQL = "select Field1,Field2 from T1"

then datagrid will have 2 columns
0
 

Author Comment

by:sainavya1215
ID: 10808199
I HAVENT USED ANY SELECT STATEMENT YET AT ALL I AM STILL IN FIRST STAGE OF USING UR CODE  

We are still not at database level instead I am just entering data for display purpose into DATAGRID (THIS IS THE FIRST CONDITION)

Again : 1st condition is that when both the 2 textboxes are filled and button1 is pressed IT SHOWS THE ENTRIES IN GRID ........We are that stage now

using this code

  ' Populate the table.
        Dim dtbatch As New DataTable()
        Dim dsbatch As New DataSet()

        Dim BatchData(2) As Object

        BatchData(0) = TextBox1.Text.Trim
        BatchData(1) = TextBox2.Text.Trim
        dtBatch.Rows.Add(BatchData)
        ' Accept the data.
        dsBatch.AcceptChanges()

        ' Attach the DataGrids to the DataTables.
        DataGrid1.DataSource = dtbatch

    End Sub
0
 

Author Comment

by:sainavya1215
ID: 10808245
i would be posting (another question for 2nd case regarding db ) exclusively for u after we are done with first stage
0
 

Author Comment

by:sainavya1215
ID: 10808302
let say we have a grid the values entered from textboxes and when button1 is pressed should represent in Grid the following way (STAGE 1/ first case)

Serial Number         End serial Number
30                               34
40                               45

So The grid displays the values entered by user from the text boxes into the grid .........We would be done with stage1.

After this comes db updation ? Hope its clear

0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10808338
From here as I understand you have an unbound grid?
(You did not populate it from the database)

If this is correct and you need to have an empty grid from the beginnig - then you have to creat an unbounbd grid

Here is an exanple

Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Private ds As DataSet
    Private dt As DataTable

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim data_column As DataColumn

        ' Build the DataSet.
        ds = New DataSet()

        ' Build the Sale table.
        dt = New DataTable("Sale")
        ds.Tables.Add(dt)

        dt.Columns.Add("Item", GetType(String))
        dt.Columns.Add("Quantity", GetType(Integer))
        dt.Columns.Add("UnitPrice", GetType(Decimal))

        data_column = dt.Columns.Add("Total", GetType(Decimal))
        data_column.Expression = "Quantity * UnitPrice"

        ' Populate the table.
        Dim sale_data(2) As Object
        sale_data(0) = "Cookie"
        sale_data(1) = 12
        sale_data(2) = 0.25
        dt.Rows.Add(sale_data)

        sale_data(0) = "Milk"
        sale_data(1) = 1
        sale_data(2) = 1.25
        dt.Rows.Add(sale_data)

        sale_data(0) = "Towel"
        sale_data(1) = 4
        sale_data(2) = 5.95
        dt.Rows.Add(sale_data)

        ' Accept the data.
        ds.AcceptChanges()

        ' Attach the DataGrids to the DataTables.
        dg.DataSource = dt
    End Sub
End Class


This example show how to create unbound grid and fill it. The technique is the same as I showed you before. Change columns name to the required and try it.
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10808468
>>After this comes db updation ?

Let's finish with the first part an dthen jump to the next
0
 

Author Comment

by:sainavya1215
ID: 10808524
Yes u got me right..........ITS UNBOUND GRID FIRST WE FILL IT from the texbox entries (THIS IS FIRST PART)  (button1 does this he can fill many entries into grid)

2nd part   (Button2 action)

AFter user fills the grid he feels that all the missing articles ranges have been entered and he wants to update the values in the database (all these values are already present in one table)

lets say :  table   (fields are   (Id, serialNumber, endSerialNumber, Status)

Now we have to write a functionality where we get the all the values  serial Number  ---- end serial Number present in the grid loop thru them as i did in the storedprocedure and update the table with status = "missing"

I am right now trying out the latest code posted by you which is UNBOUND GRID .........Hope the 2nd functionality is clear now...........
0
 

Author Comment

by:sainavya1215
ID: 10808546
There are only 3 fields in the table

 table :  ID, serialNumber,Status
0
 

Author Comment

by:sainavya1215
ID: 10808713
IT WORKS 1st PART BUT THERE IS A SMALL PROB

AFTER WE enter first and last serial numbers and press button1 it shows the entry in GRID but when u try to add another it erases the first entry and shows the latest entry( It shows the lastest entry Instead a user can enter a range of any number of missing serials) it should keep on adding entries to the grid

here is the modified code

' Populate the table.
        Dim ds As DataSet
        Dim dt As DataTable

        Dim data_column As DataColumn

        ' Build the DataSet.
        ds = New DataSet()

        ' Build the Sale table.
        dt = New DataTable("Articles")
        ds.Tables.Add(dt)

        dt.Columns.Add("serial number", GetType(Integer))
        dt.Columns.Add("end serial", GetType(Integer))

 

        ' Populate the table.
        Dim serialNumbers(1) As Object
        serialNumbers(0) = TextBox1.Text.Trim
        serialNumbers(1) = TextBox2.Text.Trim

        dt.Rows.Add(serialNumbers)
 

        ' Accept the data.
        ds.AcceptChanges()

        ' Attach the DataGrids to the DataTables.
        DataGrid1.DataSource = dt
0
 

Author Comment

by:sainavya1215
ID: 10808825
Hi boutchkine,

Hope u had seen the prob i am having  in the 1st part.

if we are done we can go to the 2nd part

Below is the posted 2nd question

2nd question Posted.........REGARDING  DB UPDATION For the values present in the unbound datagrid

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_20951559.html
0
 
LVL 28

Accepted Solution

by:
iboutchkine earned 500 total points
ID: 10812541
The code is working. Your problem that you have your code in one place and every time you define a new dataset which overrides the previous one. DO it this way and everything will work. I wrote a small project you can copy and paste to your solution


Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    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 Button1 As System.Windows.Forms.Button
    Friend WithEvents dg As System.Windows.Forms.DataGrid
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    Friend WithEvents TextBox2 As System.Windows.Forms.TextBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.Button1 = New System.Windows.Forms.Button
        Me.dg = New System.Windows.Forms.DataGrid
        Me.TextBox1 = New System.Windows.Forms.TextBox
        Me.TextBox2 = New System.Windows.Forms.TextBox
        CType(Me.dg, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(212, 216)
        Me.Button1.Name = "Button1"
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Button1"
        '
        'dg
        '
        Me.dg.DataMember = ""
        Me.dg.HeaderForeColor = System.Drawing.SystemColors.ControlText
        Me.dg.Location = New System.Drawing.Point(0, 0)
        Me.dg.Name = "dg"
        Me.dg.Size = New System.Drawing.Size(288, 96)
        Me.dg.TabIndex = 1
        '
        'TextBox1
        '
        Me.TextBox1.Location = New System.Drawing.Point(8, 112)
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.TabIndex = 2
        Me.TextBox1.Text = ""
        '
        'TextBox2
        '
        Me.TextBox2.Location = New System.Drawing.Point(180, 112)
        Me.TextBox2.Name = "TextBox2"
        Me.TextBox2.TabIndex = 3
        Me.TextBox2.Text = ""
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 266)
        Me.Controls.Add(Me.TextBox2)
        Me.Controls.Add(Me.TextBox1)
        Me.Controls.Add(Me.dg)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        CType(Me.dg, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub

#End Region

    Dim ds As DataSet
    Dim dt As DataTable
    Dim data_column As DataColumn

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' Populate the table.
        Dim serialNumbers(1) As Object
        serialNumbers(0) = TextBox1.Text.Trim
        serialNumbers(1) = TextBox2.Text.Trim

        dt.Rows.Add(serialNumbers)

        ' Accept the data.
        ds.AcceptChanges()

        ' Attach the DataGrids to the DataTables.
        dg.DataSource = dt

    End Sub

'note that I create dataset only once on a form load
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Build the DataSet.
        ds = New DataSet

        ' Build the Sale table.
        dt = New DataTable("Articles")
        ds.Tables.Add(dt)
        dt.Columns.Add("serial number", GetType(Integer))
        dt.Columns.Add("end serial", GetType(Integer))

    End Sub
End Class
0
 

Author Comment

by:sainavya1215
ID: 10812949
Excellent ..........did u look into the posted 2nd question.......as u would be more aware what i am looking for as the question part 1 and 2 started with

I greatly appreciate all the work rendered till now. thx
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10813125
yes I did. read my answer there
0
 

Author Comment

by:sainavya1215
ID: 10816630
iboutchikine,

Ur final code too works fine. but at the last line   last_serial_number it displays error saying "could not find column2"

  Dim iRow As Integer

        MsgBox("We have " & ds.Tables(0).Rows.Count & " rows, and " & ds.Tables(0).Columns.Count & " columns")

        For iRow = 0 To ds.Tables(0).Rows.Count - 1
                   'let's say serial_number in col1 andend_serial_number in col 2
                   serial_number = ds.Tables(0).Rows(iRow).Item(1)
                   end_serial_number = ds.Tables(0).Rows(iRow).Item(2) --------------HERE ERROR IS DISPLAYED
            Next
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10816708
How many columns do you have. If you have 2 columns it will be
Col0, col1

Check if this is true and change your code
serial_number = ds.Tables(0).Rows(iRow).Item(0)
end_serial_number = ds.Tables(0).Rows(iRow).Item(1)
0
 

Author Comment

by:sainavya1215
ID: 10816848
Yep it works .........Thx
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10816898
welcome
0
 

Author Comment

by:sainavya1215
ID: 10825117
Hi iboutchkine

New question on the same grid posted for u to answer .thx

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_20953961.html
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

746 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

11 Experts available now in Live!

Get 1:1 Help Now