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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

More Datagrid woes :( 1

Status
Not open for further replies.

gpalmer711

IS-IT--Management
May 11, 2001
2,445
0
0
GB
Hi All,

I'm sure this is something really simple but I am about to pull my hair out
over this.

ASP.NET - VB as Language

I have a DataGrid added to a form at design time.

At runtime I want to retrieve some data from a database and then add a few
columns with either textboxes or drop down boxes. This is no problem and I
am currently using the code below to do this.

However what I want to do is get the values from those controls when a
button is pressed at the bottom of the form. I don't seem able to reference
the controls at all and when the form is posted back, on the button press,
the controls disappear.

Any point in the right direction would be greatly appreciated.

Regards

Greg Palmer

Code:
Public Sub DisplayPlayers()

Dim mySQL As String = ""

Dim DS As New DataSet

Dim strConnString As String = 
ConfigurationManager.ConnectionStrings("XBLA").ConnectionString

Dim objSQLAdapter As New SqlDataAdapter("SELECT * FROM [xbla_teams] WHERE 
season_ID = " & selSeason.SelectedValue.ToString, strConnString)

objSQLAdapter.Fill(DS, "[xbla_teams]")

If DS.Tables(0).Rows.Count > 0 Then

mySQL = mySQL & "sql goes here "

Dim myRow As Integer

For myRow = 0 To DS.Tables(0).Rows.Count - 1

If myRow = 0 Then

mySQL = mySQL & "sql goes here  "

Else

mySQL = mySQL & "sql goes here  "

End If

Next

mySQL = mySQL & "sql goes here

Else

mySQL = mySQL & "SELECT [xblaleagues].[dbo].[xbla_users].[gamertag] as 
GamerTAG "

mySQL = mySQL & "sql goes here "

End If

Dim DS1 As New DataSet

Dim objSQLAdapter1 As New SqlDataAdapter(mySQL, strConnString)

objSQLAdapter1.Fill(DS1, "[xbla_players]")

playersGrid.DataSource = DS1.Tables(0)

'code for each round

Dim DS2 As New DataSet

Dim objSQLAdapter2 As New SqlDataAdapter("sql goes here ", strConnString)

objSQLAdapter2.Fill(DS2)

Dim intRounds As Integer

For intRounds = 0 To DS2.Tables(0).Rows.Count - 1

Dim tc1 As New TemplateField()

If DS2.Tables(0).Rows(intRounds).Item("round_type").ToString = "Points" Then

tc1.ItemTemplate = Page.LoadTemplate("pointsTemplate.ascx")

tc1.EditItemTemplate = Page.LoadTemplate("pointsTemplate.ascx")

ElseIf DS2.Tables(0).Rows(intRounds).Item("round_type").ToString = 
"Position" Then

tc1.ItemTemplate = Page.LoadTemplate("positionTemplate.ascx")

tc1.EditItemTemplate = Page.LoadTemplate("positionTemplate.ascx")

End If

tc1.HeaderText = DS2.Tables(0).Rows(intRounds).Item("round_name").ToString

playersGrid.Columns.Add(tc1)

Next

playersGrid.DataBind()

DS.Dispose()

objSQLAdapter.Dispose()

End Sub
Click event on button
Code:
Protected Sub cmdAddPoints_Click(ByVal sender As Object, ByVal e As 
System.EventArgs) Handles cmdAddPoints.Click

Dim strMsg As String = ""

strMsg = "Number of rows = " & playersGrid.Rows.Count.ToString & vbCrLf

strMsg = strMsg & "Number of Columns = " & 
playersGrid.Columns.Count.ToString & vbCrLf

strMsg = strMsg & "Has Controls = " & 
playersGrid.Rows(0).Cells(0).HasControls.ToString '----This always comes out 
as false

MsgBox(strMsg)

End Sub
 
when the form is posted back, on the button press,
the controls disappear
It sounds as though you are creating dynamic controls but you are not creating them on every load of the page.


____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
Hi Mark,

That is correct, However if I cannot get the value from the control then having them load at every page load is a mute point. As assuming that people have added data to the text boxes, when the page is reloaded and the controls are created again I can not populate them with the data that the person added before the postback.

Basically the situation is this.

Site for running leagues on Xbox games. Each weeks competition is split into rounds, the number of rounds could be anything. So the code that I used above will get a list of the players for that week, and the team names if there are any. These are then bound to the DataGrid.

I then retrieve the number of rounds and type of round and then load the relevant template column.

All this works fine, however something that I thought would be simple is taking me way too long to figure out. I'm guessing that I am missing something simple or that the way that I am trying to do it will just not work. Either way google has not been my friend on this problem and I would really appreciate a point in the right direction, even if this means that I have to totally change the way that I am doing this.

Regards

Greg
 
That is correct, However if I cannot get the value from the control then having them load at every page load is a mute point. As assuming that people have added data to the text boxes, when the page is reloaded and the controls are created again I can not populate them with the data that the person added before the postback.
Don't worry about that for now, as dynamically created controls will retain their values automatically via viewstate. For example, try this and add some data before pressing the button:
Code:
    <form id="form1" runat="server">
        <div>
            <asp:Panel ID="Panel1" runat="server">
            </asp:Panel>
            <asp:Button ID="Button1" runat="server" Text="Button" />
        </div>
    </form>
Code:
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim t As TextBox

        For i As Integer = 0 To 10
            t = New TextBox
            t.ID = "txt" & i
            Panel1.Controls.Add(t)
        Next
    End Sub



____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
Hi Mark,

Thanks for that, i'm not sure that it is going to work given the way that the code is at the moment.

Basically the DataGrid already exists on the page and then columns are added to it. If I add the code to the pageload so the controls are created again. It basically adds x number of columns again and removes the controls from the existing columns.

However I think that if I create the whole datagrid dynamically then this should work fine.

Greg
 
Thanks Mark - if you need any more of the source code let me know.

Greg
 
OK, it looks as though you have to load the template and rebind the grid (at least in the test I've done). However, this may cause problems depending on what you are doing later on with the grid. Here's an example I came up with anyway:
Code:
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField DataField="Column1" />
                    <asp:BoundField DataField="Column2" />
                </Columns>
            </asp:GridView>
            <asp:Button ID="Button1" runat="server" Text="Click Me" />
        </div>
    </form>
Code:
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

            Dim tc As New TemplateField
            tc.HeaderText = "New Column"
            tc.ItemTemplate = Page.LoadTemplate("WebUserControl.ascx")
            GridView1.Columns.Add(tc)
        Else

            Dim tc As New TemplateField
            tc = CType(GridView1.Columns(2), TemplateField)
            tc.HeaderText = "New Column"
            tc.ItemTemplate = Page.LoadTemplate("WebUserControl.ascx")
        End If

        GridView1.DataSource = GetData()
        GridView1.DataBind()
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Response.Write(System.DateTime.Now)
    End Sub

    Private Function GetData() As DataTable
        ' Declarations  
        Dim dt As New DataTable
        Dim dr As DataRow

        ' Add some columns  
        dt.Columns.Add("Column1")
        dt.Columns.Add("Column2")

        ' Add some test data
        For i As Integer = 0 To 10
            dr = dt.NewRow
            dr("Column1") = i
            dr("Column2") = "Value " & i
            dt.Rows.Add(dr)
        Next

        ' Return the DataTable  
        Return dt
    End Function


____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
Hi Mark,

I've had a play with that and I'm sure that I can now adapt my code to fit in with that.

Many Thanks

Greg
 
Right,

I now almost have the code working perfectly thanks to Marks suggestion.

Here is an example of the datagrid



For some reason it is adding the Team and Player fields in twice.

The problem does not occur using Marks' code, but I fail to see any glaring differences in my code.

Datagrid Code
Code:
<asp:GridView EnableViewState="true" Enabled="true" ID="playersGrid" runat="server">
        <Columns>
            <asp:BoundField DataField="TeamName" HeaderText="Team Name" />
            <asp:BoundField DataField="GamerTag" HeaderText="GamerTag" />
        </Columns>
    </asp:GridView>

Code Behind page
Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
                SqlDataSource1.SelectCommand = "sql is here"
            Else
                'DisplayPlayers()
                buildRounds(True)
                playersGrid.DataSource = getPlayers()
                playersGrid.DataBind()

            End If
            
        End If
    End Sub

    
Public Function getPlayers() As Data.DataTable
        Dim mySQL As String = ""
        Dim DS As New DataSet
        Dim strConnString As String = ConfigurationManager.ConnectionStrings("XBLA").ConnectionString
        Dim objSQLAdapter As New SqlDataAdapter("SQL is HERE", strConnString)
        objSQLAdapter.Fill(DS, "[xbla_teams]")
        If DS.Tables(0).Rows.Count > 0 Then
            mySQL = mySQL & "SQL is HERE"
            Dim myRow As Integer
            For myRow = 0 To DS.Tables(0).Rows.Count - 1
                If myRow = 0 Then
                    mySQL = mySQL & "SQL is HERE"
                Else
                    mySQL = mySQL & "SQL is HERE"
                End If
            Next
            mySQL = mySQL & "SQL is HERE"
        Else
            mySQL = mySQL & "SQL is HERE"
        End If
        Dim DS1 As New DataSet
        Dim objSQLAdapter1 As New SqlDataAdapter(mySQL, strConnString)
        objSQLAdapter1.Fill(DS1, "[xbla_players]")
        Dim dt As New Data.DataTable
        Dim dr As Data.DataRow
        dt.Columns.Add("TeamName")
        dt.Columns.Add("GamerTag")

        For i As Integer = 0 To DS1.Tables(0).Rows.Count - 1
            dr = dt.NewRow
            dr("TeamName") = DS1.Tables(0).Rows(i).Item("TeamName").ToString
            dr("GamerTag") = DS1.Tables(0).Rows(i).Item("GamerTag").ToString
            dt.Rows.Add(dr)
        Next

        DS.Dispose()
        objSQLAdapter.Dispose()
        Return dt
    End Function

    Public Sub buildRounds(Optional ByVal blnPostback As Boolean = False)
        Dim DS2 As New DataSet
        Dim strConnString As String = ConfigurationManager.ConnectionStrings("XBLA").ConnectionString
        Dim objSQLAdapter2 As New SqlDataAdapter("SQL is HERE", strConnString)
        objSQLAdapter2.Fill(DS2)
        Dim intRounds As Integer
        For intRounds = 0 To DS2.Tables(0).Rows.Count - 1
            Dim tc1 As New TemplateField
            If blnPostback = False Then
                If DS2.Tables(0).Rows(intRounds).Item("round_type").ToString = "Points" Then
                    tc1.ItemTemplate = Page.LoadTemplate("pointsTemplate.ascx")
                    tc1.EditItemTemplate = Page.LoadTemplate("pointsTemplate.ascx")
                ElseIf DS2.Tables(0).Rows(intRounds).Item("round_type").ToString = "Position" Then
                    tc1.ItemTemplate = Page.LoadTemplate("positionTemplate.ascx")
                    tc1.EditItemTemplate = Page.LoadTemplate("positionTemplate.ascx")
                End If
                tc1.HeaderText = DS2.Tables(0).Rows(intRounds).Item("round_name").ToString
                playersGrid.Columns.Add(tc1)
            Else
                tc1 = CType(playersGrid.Columns(intRounds + 2), TemplateField)
                If DS2.Tables(0).Rows(intRounds).Item("round_type").ToString = "Points" Then
                    tc1.ItemTemplate = Page.LoadTemplate("pointsTemplate.ascx")
                    tc1.EditItemTemplate = Page.LoadTemplate("pointsTemplate.ascx")
                ElseIf DS2.Tables(0).Rows(intRounds).Item("round_type").ToString = "Position" Then
                    tc1.ItemTemplate = Page.LoadTemplate("positionTemplate.ascx")
                    tc1.EditItemTemplate = Page.LoadTemplate("positionTemplate.ascx")
                End If
            End If
        Next
    End Sub
 
My example set the DataSource method and then called the DataBind method on each page load whereas you only appear to be calling it if it isn't a postback (notice how I set it outside the Page.IsPostback if statement so that it is always called).

However, if you do this on every page load, I think it will cause you some problems when you try to capture the user's input. If that does happen, it may mean that you have to create the GridView dynamically as well.


____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
Hi Mark,

The page also contains some Dropdown boxes that are databound. When the 3rd of 3 dropdown boxes are bound the following is also called else where in the code.

Code:
buildRounds(True)
                playersGrid.DataSource = getPlayers()
                playersGrid.DataBind()

So far capturing the data has been fine, it is just those extra two columns that seem to be causing me problems. Although to be honest i've not looked at it much since my last post above.

Thanks

Greg
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top