开发者

Why does my counter variable not increment in this VB.NET code sample?

开发者 https://www.devze.com 2022-12-18 11:23 出处:网络
I have the following code Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click

I have the following code

Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click

    Dim counter As Integer = 0
    Dim t As DataTable = DirectCast(Session("MyDataTable"), DataTable)
    Dim row1 As DataRow = t.NewRow()



    If (isUnique(t) And counter < 30) Then
        row1("ID") = counter + 1
        row1("univirsityID") = ddlUnivs.SelectedValue
        row1("majorID") = ddlMajors.SelectedValue
        row1("UniName") = ddlUnivs.SelectedItem.Text
        row1("MajorName") = ddlMajors.SelectedItem.Tex开发者_如何转开发t
        t.Rows.Add(row1)
        Session("MyDataTable") = t
        GridView1.DataSource = t
        GridView1.DataBind()
        lblMsg.Text = "تم اضافة الرغبة"
        counter = counter + 1

    Else
        lblMsg.Text = "سبق لك ادخال الرغبة"
    End If

End Sub

The problem is the row1("ID") dose not change it keeps getting the value of 1 for all rows added to datatable any help is appreciated thanks in advance.


Remove your current counter declaration (for the reasons everyone has been posting) and put this on top of your class:

Public Property Counter() As Integer
     Get
         Return IIf(ViewState("counter") Is Nothing, 0, CInt(ViewState("counter")))
     End Get
     Set(ByVal value As Integer)
         ViewState("counter") = value
    End Set
End Property

This way you are saving your counter variable in the statefull ViewState of your page, and it won't get lost after a page-cycle.


With this line

Dim counter As Integer = 0

You are setting the counter every single time you click the button.

You need to store the counter in session or some other way.


Counter will always be 0 as you reinitialise it on entry to the method.

Is there supposed to be a for loop in there somewhere?


The problem is that you're initializing the counter variable to 0 every time that you click the button. You will need to move counter to the next higher level and save it somewhere between postbacks. I would suggest creating a session variable and saving it in there.


I'd venture to guess you're actually looking for an identity column in the database. Otherwise your ID could be duplicated, which is no bueno.

Are you looking to do a loop in this code? There's no loop, so counter starts out at zero and gets 1 added. This could only insert one row.


counter is a local variable, and it's going out of scope when the sub ends. That's why it is not incrementing.

0

精彩评论

暂无评论...
验证码 换一张
取 消