简体   繁体   中英

Change tables loaded in the grid with dropdownlist

I am doing this for my own learning. It is not home work. All example I have found are for asp solutions.

I have a Grid and a DropDownList in a Winform . The Grid has a DataSet a BindingSource and a TableAdapter . I populate the dropdownlist with the tables in the DB as following:

public  void FillDropDownList(string connString)
    {
        String Query = "SELECT * FROM information_schema.tables where Table_Name like 'Table%'";
        using (var cn = new SqlConnection(connString))
        {
            cn.Open();
            DataTable dt = new DataTable();
            try
            {
                SqlCommand cmd = new SqlCommand(Query, cn);
                SqlDataReader myReader = cmd.ExecuteReader();
                dt.Load(myReader);
            }
            catch (SqlException e)
            {
               //to be completed
            }

            radDropDownList1.DataSource = dt;
            radDropDownList1.ValueMember = "TABLE_NAME";
            radDropDownList1.DisplayMember = "TABLE_NAME";
        }
    }

The line that loads the data in the grid is like this:

 this.table_xxxTableAdapter.Fill(this.xxxDataSet.Table_xxx);

So I suspect that with these components I would need a new dataset for each table but I do not like to do that because new tables may be created in the future.

How can I change the table loaded in the grid selecting tables from the dropdownlist?

A DataSet requires that you specify the tables you may want to load at design time, but it sounds like you want to load these tables dynamically (because they may get added to the database from another source?)

If I'm understanding your question correctly, you should simply do this:

Whenever the user selects a table, load the selected table using a dynamic query and re-databind the grid to it. The code should look something like this. Note: This is untested code.

protected void radDropDownList_OnSelectedIndexChanged(object sender, EventArgs e)
{
    DataTable dt = new DataTable();

    string query = BuildQuery(radDropDownList.SelectedValue);  //Pass in the table name
    using (var cn = new SqlConnection(connString))
    {
        cn.Open();
        try
        {
            SqlCommand cmd = new SqlCommand(query, cn);
            using (var da = new SqlDataAdapter(cmd))
            {
                ad.Fill(dt);
            }
        }
        catch (SqlException e)
        {
           //TODO: Handle this exception.
        }
    }

    radGrid.DataSource = dt;
    radGrid.DataBind();
}

private string BuildQuery(string table)
{
    //TODO:  Provide your own implementation for your query.
    return string.Format(
        @"SELECT * FROM {0}", table);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM