DataSet's DataTable's and TableAdapter's Oh My!

Here is my situation.  I am using VB as my programming language.

I am creating a part of a website that will be the admin section.  I want the admin to be able to add/edit data in a set of tables that normal users can't.  There are 20 lookup tables that I use in the website that I want the admin to be able to manage (i.e. add, edit, delete, insert).  I don't want to create 20 separate web pages (one for each table).  I have one page that has links to all the tables.  Each link has a "table" querystring variable associated with it.  When the admin clicks on the link it will send the user to the GridView page.  The GridView page will get the "table" querystring variable, then load a GridView based on that variable.  I have created the Data Access Layer with DataTables and TableAdapters setup for the 20 Lookup Tables.

Here is the code that I have so far.  The main part that I cannot seem to figure out is how to choose the appropriate DataTable based on the "table" querystring variable.  I would rather not have to create a huge Case statement.

 

Imports dsPART_CONVTableAdapters   'Imports the Table Adapters class I created in the DLL
Imports System.Data

Partial Class managing_lookup
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim strTableName As String

        'Sets strTableName equal to the passed in querystring variable table 
        strTableName = Request.QueryString("table")

        LoadGrid(strTableName)

        If Not IsPostBack Then
            AddColumnsToGrid(strTableName)
        End If

       
    End Sub

    Protected Sub LoadGrid(ByVal strTableName As String)
        With Me.ObjectDataSource1
            .SelectMethod = "GetData"           'All of my TableAdapters Select Statements are called GetData
            .DeleteMethod = "Delete"
            .InsertMethod = "Insert"
            .UpdateMethod = "Update"
            .OldValuesParameterFormatString = "Original_{0}"
        End With

        'Set Type Name
        Me.ObjectDataSource1.TypeName = "dsPart_CONVTableAdapters." & strTableName & "TableAdapter"

        'Update Parameters
        SetUpdateParameters(strTableName)

        'Insert Parameters
        SetInsertParameters(strTableName)

        'Delete Parameters
        Me.ObjectDataSource1.DeleteParameters.Add("Original_{0}", TypeCode.Int32)

    End Sub

    Protected Sub SetUpdateParameters(ByVal strTableName As String)

        Dim strDataTableName As String = "dsPart_CONV." & strTableName & "DataTable"

        Dim datTable As New DataTable

        'Would Like to set datTable equal to what is in strDataTableName
        
        'Need to find a way to set datTable to the DataTable's set in the DLL

        For Each col As DataColumn In datTable.Columns
            Me.ObjectDataSource1.InsertParameters.Add(col.ColumnName, col.DataType.ToString) 'Do I Need Data Type
        Next

        Me.ObjectDataSource1.InsertParameters.Add("Original_{0}", TypeCode.Int32)

    End Sub

    Protected Sub SetInsertParameters(ByVal strTableName As String)
        'same as set update parameters find way to dynamically set datTable based on strTableName
        Dim strDataTableName As String
        strDataTableName = "dsPart_CONV." & strTableName & "DataTable"

        'Sets DataTable equal to passed strTableName
        Dim datTable As New DataTable
        datTable.TableName = strTableName

        For Each col As DataColumn In datTable.Columns
            Me.ObjectDataSource1.InsertParameters.Add(col.Caption, col.DataType.ToString)
        Next

    End Sub

    Protected Sub AddColumnsToGrid(ByVal strTableName As String)
        'same as set update parameters find way to dynamically set datTable based on strTableName
        Dim strDataTableName As String
        strDataTableName = "dsPart_CONV." & strTableName & "DataTable"

        'Sets DataTable equal to passed strTableName
        Dim datTable As New DataTable
        datTable.TableName = strTableName

        With GridView1
            .DataSourceID = "ObjectDataSource1"
            .AutoGenerateColumns = False
            .DataKeyNames = New String() {"ID"}
            .AllowPaging = True
            .AllowSorting = True
            .PageSize = 10
        End With

        Dim bf As New BoundField
        For Each col As DataColumn In datTable.Columns
            With bf
                .HeaderText = col.ColumnName
                .DataField = col.ColumnName
                .SortExpression = col.ColumnName
            End With
            Me.GridView1.Columns.Add(bf)
        Next

       
        Dim cmdField As New CommandField

        With cmdField
            .ButtonType = ButtonType.Button
            .ShowCancelButton = True
            .ShowEditButton = True
            .ShowDeleteButton = True
        End With
    End Sub
End Class

 

0
shepujw
5/30/2007 2:35:32 PM
asp.net.object-datasource 16182 articles. 0 followers. Follow

2 Replies
777 Views

Similar Articles

[PageSpeed] 53

Hi,

To query table according to the table name and bind, I suggest your TableAdapter take the query string as the table name, just as you do it in AddColumnsToGrid() method.

You can pass the table name to the lower level to make it query from the desired table and then bind it to the grid. However, the TableAdapter wizard might not allow you to do this, so you have to customize it. Add some custom methods to the TableAdapter to wrap the GetData() method.

Here are some articles for your reference.

http://msdn2.microsoft.com/en-us/library/ms233697(VS.80).aspx

HTH. If this does not answer your question, please feel free to mark the post as Not Answered and reply. Thank you!


Sincerely,
Kevin Yu
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Mark as Not Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
0
Kevin
6/4/2007 3:18:48 AM

I have modified the code and everything works now.  I do not understand your recommendation:  "I suggest your TableAdapter take the query string as the table name, just as you do it in the AddColumnsToGrid() Method".  Could your provide me with a very short working example?

Here is the code that works.  I had to modify some of the bound field code and add a CASE statement to pull in the correct DataTable.  I wish I wouldn't have to use the table adapter and I could just select the correct one based on the "table" querystring variable.

Imports dsPART_CONVTableAdapters
Imports System.Data

Partial Class managing_lookup
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim strTableName As String

        strTableName = Request.QueryString("table")

        LoadGrid(strTableName)

        If Not IsPostBack Then
            AddColumnsToGrid(strTableName)
        End If

       
    End Sub

    Protected Sub LoadGrid(ByVal strTableName As String)
        With Me.ObjectDataSource1
            .SelectMethod = "GetData"  'Need to change all table adapters to GetData
            .DeleteMethod = "Delete"
            .InsertMethod = "Insert"
            .UpdateMethod = "Update"
            .OldValuesParameterFormatString = "Original_{0}"
        End With
        'Set Type Name
        Me.ObjectDataSource1.TypeName = "dsPart_CONVTableAdapters." & strTableName & "TableAdapter"

        'Update Parameters
        SetUpdateParameters(strTableName)

        'Insert Parameters
        SetInsertParameters(strTableName)

        'Delete Parameters
        Me.ObjectDataSource1.DeleteParameters.Add("Original_{0}", TypeCode.Int32)

       

    End Sub

    Protected Sub SetUpdateParameters(ByVal strTableName As String)

        'Dim strDataTableName As String
        'strDataTableName = "dsPart_CONV." & strTableName & "DataTable"

        'Sets DataTable equal to passed strTableName
        Dim datTable As DataTable = GetDataTable(strTableName)

        For Each col As DataColumn In datTable.Columns
            Me.ObjectDataSource1.InsertParameters.Add(col.ColumnName, col.DataType.ToString) 'Do I Need Data Type
        Next

        Me.ObjectDataSource1.InsertParameters.Add("Original_{0}", TypeCode.Int32)

    End Sub

    Protected Sub SetInsertParameters(ByVal strTableName As String)
        'same as set update parameters find way to dynamically set datTable based on strTableName
        'Dim strDataTableName As String
        'strDataTableName = "dsPart_CONV." & strTableName & "DataTable"

        'Sets DataTable equal to passed strTableName
        Dim datTable As DataTable = GetDataTable(strTableName)

        For Each col As DataColumn In datTable.Columns
            Me.ObjectDataSource1.InsertParameters.Add(col.Caption, col.DataType.ToString)
        Next

    End Sub

    Protected Sub AddColumnsToGrid(ByVal strTableName As String)
        'same as set update parameters find way to dynamically set datTable based on strTableName
        'Dim strDataTableName As String
        'strDataTableName = "dsPart_CONV." & strTableName & "DataTable"

        'Sets DataTable equal to passed strTableName
        Dim datTable As DataTable = GetDataTable(strTableName)

        With GridView1
            .DataSourceID = "ObjectDataSource1"
            .AutoGenerateColumns = False
            .DataKeyNames = New String() {"ID"}
            .AllowPaging = True
            .AllowSorting = True
            .PageSize = 10
        End With


        For Each col As DataColumn In datTable.Columns
            Dim bf As New BoundField
            With bf
                .HeaderText = col.ColumnName
                .DataField = col.ColumnName
                .SortExpression = col.ColumnName
            End With
            Me.GridView1.Columns.Add(bf)
            bf = Nothing
        Next

       
        Dim cmdField As New CommandField

        With cmdField
            .ButtonType = ButtonType.Button
            .ShowCancelButton = True
            .ShowEditButton = True
            .ShowDeleteButton = True
        End With
        Me.GridView1.Columns.Add(cmdField)
    End Sub

    Public Function GetDataTable(ByVal strTableName As String) As DataTable
        Select Case strTableName
            Case "tblLookup_BsktSlsCat"
                GetDataTable = New dsPART_CONV.tblLookup_BsktSlsCatDataTable
            Case "tblLookup_BsktState"
                GetDataTable = New dsPART_CONV.tblLookup_BsktStateDataTable          
            '(around 15 more case statments showing all datatables continue on.  I deleted them because the code is so long.)
        End Select
    End Function
End Class
 

0
shepujw
6/4/2007 4:59:20 PM
Reply:

Similar Artilces:

Replace 1's and 0's in a gridview column with Yes's and No's
Is it possible to change the display of a column in a gridview to show a Yes for all 1's and a No for 0's that display in a particular column of a gridview bound to a database?  If so, can someone share the way with me?  I am using ASP.NET 2.0 with VB Code Behind.  Thanks One way you can do is thrrough  CASE in your select statement: Select YesNoColumn= CASE yourColumn WHEN 1 THEN 'Yes' WHEN 0 THEN 'No' ELSE '' END FROM YourtableLimno <Columns>     <asp:TemplateField HeaderText="yourHeader" SortExpression="yourDataField"> ...

It's Linux !? No, it's BSD ! No, no, it's...
kFreeBSD http://wiki.debian.org/Debian_GNU/kFreeBSD a Debian distro using the FreeBSD kernel ! ObiWan wrote: > kFreeBSD > > http://wiki.debian.org/Debian_GNU/kFreeBSD > > a Debian distro using the FreeBSD kernel ! Why use a BSD kernel? I hope the reason is more than, just because they can. http://wiki.debian.org/Debian_GNU/kFreeBSD_why It's easy to understand why the would want to use Debian packages. :) -- Jimmy Johnson Registered Linux User #380263 >> kFreeBSD >> >> http://wiki.debian.org/Debian_GNU/kFreeBSD >> ...

Help! I cannot access the DataGrid's ItemTemplate's LinkButton's Text Atrribute 's Value!!!!!!!!!!!
I write a datagrid's ItemDataBound method as follows:   private void dgTable_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)  {   if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)   {    if(!isRole("Manager"))    {     LinkButton tmp = (LinkButton)e.Item.FindControl("lbPassed");     if(tmp.Text == "Passed")     {      ((LinkBu...

Hyperlink's, ImageURL's, and OnError's
I created an ASP:Hyperlink and set the ImageURL attribute so the link will be the image.If the image is missing, I would like it to display a 'missing image' pic that I have.  I know you can use the OnError attribute of the <img> tag to run some javascript to change it.Unfortunately I can't find a way to access the Hyperlink's Image that is inside it, so I can add an Attribute so the resulting <img> tag will have an OnError attribute inside of it.Any help?If my Hyperlink is called 'foo'....would I do...  ((Image) foo.Controls[0]).Attributes.Add(&...

Guru's..?? Any do's and/or dont's for Zfd4 and Citrix..?
We've got a nw6/sp5 network with GW 6.5, bm3.7 and zfd 4.01 up'n'running.. Now we're adding a citrix server ( win2003) to the mix, will supply a couple off app's to users over the internal VPN in another city. Probably we'll skip the AD phase since we can not see any app and/or user with the need for AD. So,, any special considorations..? tip's'tricks..? known issues...? t.i.a... On Mon, 16 Aug 2004 15:57:10 GMT, Emerson wrote: > So,, any special considorations..? tip's'tricks..? known issues...? biggest one... zfd4.x d...

Who's show is SN? Steve's or Leo's?
I don't want to start anything (honestly)! Just want to ask a simple question. Does the Security Now podcast belong to Steve Gibson or Leo Laporte? Maybe I'm in a world all to myself, but when I listen to the excellent SN podcasts, I want to hear STEVE, not Leo. But especially in the past few shows, it seems Leo will repeatedly interrupt Steve in the middle of a sentence that I want to hear the rest of. I consider this very rude of Leo. Steve is making a point that I (we) want to hear, then looses his train of thought after Leo barges in and asks something. It...

411 it's pconsole, 51 it's NWPMW32, 65 it's ???
I like to give some of my users controll over their print jobs. In Netware 3.x to 4.x it was pconsole. In Netware 5.x it was NWPMW32. I don't seem to be able to find the same type of utility for Netware 6.5? We don't like to give user access to nwadmin and the NWPMW32 I copied from my 51 server (TID 10075273) to the 65 server won't display the jobs. Mmccabe, It appears that in the past few days you have not received a response to your posting. That concerns us, and has triggered this automated reply. Has your problem been resolved? If not, you might try o...

Repost: FF won't show gif's nor jpg's Red X's
XP sp2 FF 2.0.0.4 extentions: Adblock Plus Copy plain text Fasterfox Firebug FireFTP McAfee SiteAdvisor NoScript Talkback Video Downloader Pic's show red x's. These pics show just fine in Internet Explorer and Netscape. Anyone have any ideas????? Fasterfox, I guess. See what happens if you disable it (or just disable its pipelining feature). -- �Q� =============== Thank you Q. I disabled all of them, one at a time (restarting each time) and the problem still exists :-( digimomma On 7/12/2007 5:26 PM digimom inquired: > Thank y...

The value's length for key 'data source' exceeds it's limit of '128'.
Hii, When I tried to bind dropdownlist to database by declaring connection string in the code behind file I am getting this error: The value's length for key 'data source' exceeds it's limit of '128'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: The value's length for key 'data source' exceeds it's limit of '128'.Source Error: An...

Trojans, PUP's and virus's in GRC NG's Hmmm
Hmm, Just connected a new client that caused a refresh of the group. Multiple postings were intercepted as containing trojans and other such. Even one in grc.news, which only Steve can port to (as far as I know) Is this expected.. IE you guys are discussing the mechanics of trojans etc, with code examples? Dave 09/11/2008 19:41:38 Deleted HOSTNAME\USERNAME C:\Program Files\Windows Live\Mail\wlmail.exe C:\Sandbox\USERNAME\LiveMailnOE\user\current\Local Settings\Application Data\Microsoft\Windows Live Mail\news.grc.com\grc.news\11AB78DB-00000117.nws Exploit-CodeBase.g...

It's not about 1st amendment, it's about condoning Mozilla's despicable behavior.
Today I got a nice email from someone inside Mozilla, in response to my ang= ry post elsewhere, explaining Mozilla's actions. He ended his email with: "Open dialogue is an important part of Mozilla's commitment to open, honest= and community-driven communication, and we remain committed to a free, ope= n web." In the spirit of open dialogue, let me share here my response to him. Ze'ev --------- Dear ..., I appreciate your position yet I remain convinced that Mozilla's behavior w= as despicable. Mozilla caved in to public pressure about one of i...

Sybase Ver wise SysTab's, Proc's and add-on info's !!!
Hi DBA Team, Any one is having table formatted information or an excel sheet which will have a clear picture about Sybase Version wide details on System Tables, Procedures and add-on=92s features right from Sybase 4.x to up to date. This will be serving more clarification on Sybase DBA=92s World to know about Sybase version wide comparative changes, features and upcoming details. Experienced DBA=92s are already known this information on their minds. Kindly spare your time to share the same across the WORLD. Thanks In Advance Regards, Viswanathan.V Sybase DBA Practice ...

NtCanuck's `TreeWalk' and AnalogX's `FastCache' Dns Servers
Hello Global Friends, I have been using AnalogX's "FastCache" software as my Local Dns Server for all these years. For the last three years I did not see a new version of FastCache software. Recently I came to know of (Developers NT Canuck & ObiWan) "Tree Walk" Dns Server and started using it in the place of FastCache. Tree Walk works perfectly but some offline web pages could not load in IE6. http://www.nseindia.com/marketinfo/charting/HistStockChart.jsp?plot1=TRD_QTY&plot2=PRICE&symbol=colgate&indexname=S%26P+CNX+NIFTY&stdate=01&stm...

changes made from one user's webpart's page, effects all user's
 I am just doing this offline right now in Visual Web Developer Express 2008I created the login inonce in the memberpage area, people can modify their webpart page. I created several users to test this out.  I loaded it in a browser.When I make changes as logged in user "A" .  Then logout and login as user "B", user "B,s" webpart page has been changed to user "A".This goes true for whomever I log in as.  It changes for everyone.Is there something specific I need to do in order to get everyone's changes to be unique for them...

Web resources about - DataSet's DataTable's and TableAdapter's Oh My! - asp.net.object-datasource

Resources last updated: 1/3/2016 7:45:03 AM