1

How can I create a gridview control in c# asp.net which acts like an mssql database? I mean, I have a dropdownlist which the items represent the table names in the database and the gridview is constructed on the selected table name. So basically, the gridview display data from whatever table is selected in the dropdownlist. I want to edit, insert or delete rows from the database using this gridview. Any suggestions?

Shaokan
  • 7,438
  • 15
  • 56
  • 80

4 Answers4

2

In a gridview You can easily Bind all the values of a table by the use of the Query.

string selectSQL = String.Format("SELECT * FROM [{0}]", ddlTable.SelectedItem.Text);

just set AutoGenerateColumns="True"

now in the gridview you can enable the Command field in it will help you to this you can find in Column Property of GridView. By using this You can Edit Delete select any row in the GridTable.

<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowSelectButton="True" />
<asp:CommandField ShowDeleteButton="True" />  
Vir
  • 1,294
  • 1
  • 13
  • 23
  • sorry that's my bad I had to be more specific, I can already fetch data from each table without any problem but how can I set a dynamic updatecommand? I mean once I select the table in the dropdownlist, the gridview displays the relevant data, there is no problem till there, but how about the update command? since every table has a different structure do I have to create the updatecommand in code behind for each table seperately or is there any automatic way to do this? – Shaokan May 21 '11 at 09:38
  • did you try the LINQ to fetch ,update or delete .if you use that than u have to write each table data specifically – Vir May 21 '11 at 12:03
0

You'll need to create a dynamic query using the selected table name from drop down. Execute it against the database and bind the results back to the gridview.

See this example for an example

You'll need to do something like this-

    string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
    string selectSQL = String.Format("SELECT * FROM [{0}]", ddlTable.SelectedValue);

    //execute query, fill dataset

    GridView1.DataSource = ds;
    GridView1.DataBind();

Also, you may want to see how to get List of all tables in database

Community
  • 1
  • 1
YetAnotherUser
  • 9,156
  • 3
  • 39
  • 53
  • Yeah I have no problems till here, but how about the updatecommand? I have to specify an updatecommand and what if the tables are dynamic? – Shaokan May 21 '11 at 10:38
0

If you want to generate the list of tables dynamically in your ddl then you can have a look here, You can also make use of this link, which will help you to INSERT,DELETE,UPDATE with the gridView.

Hope it helped :)

painotpi
  • 6,894
  • 1
  • 37
  • 70
0

As I could not find a solution to this problem I've decided to create a table dynamically and create the update / insert commands referencing some rows in the table.

Shaokan
  • 7,438
  • 15
  • 56
  • 80