We help IT Professionals succeed at work.

Windows forms DataGrid  adding items

sainavya1215
sainavya1215 asked
on
1,300 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?
Comment
Watch Question

Commented:
use a DataSet? Is this what you want to know?
   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

Author

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

Author

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

Author

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

Author

Commented:
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 ?

Author

Commented:
hi iboutchkine,
was it clear. It would be greatly appreciated if you could help me out regarding this though
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.

Author

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

Author

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

Author

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

Author

Commented:
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
>>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
Change this line
  Dim BatchData(2) As Object
 

to


  Dim BatchData(1) As Object



Author

Commented:
same prob exists i tried that too
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

Author

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

Author

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

Author

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

Author

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

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.
>>After this comes db updation ?

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

Author

Commented:
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...........

Author

Commented:
There are only 3 fields in the table

 table :  ID, serialNumber,Status

Author

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

Author

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

https://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_20951559.html
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
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
yes I did. read my answer there

Author

Commented:
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
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)

Author

Commented:
Yep it works .........Thx
welcome

Author

Commented:
Hi iboutchkine

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

https://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_20953961.html
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.