简体   繁体   中英

Cycle Through Sql Columns

I am working with a gridview in C# and I am wondering if there is an effective way to use one data source instead of three. Right now I have an if statement that selects the Data Source based off the value in a dropdownlist, ddlType.

if (ddlType.Text == "Confirmation")
    gvMailMergeExport.DataSourceID = "SqlDSConfirmation";
else if (ddlType.Text == "Cancellation")
    gvMailMergeExport.DataSourceID = "SqlDSCancellation";
else
    gvMailMergeExport.DataSourceID = "SqlDSPreArrival";

Because each Database needs to look at a different column in the same table to decide which data to show. The three columns being used are ConfirmationEmail, CancellationEmail, and PreArrivalEmail. Each of these three columns is a bit value and I only display the rows where the correct column has a '0' for it's value. So question: is there anything like @ColumnName = 0 that would work for this? Thank you.

I've never used SQLDataSources, but if you want to go the more custom route, you could build out your query (or use LINQ to SQL or LINQ to Entity Framework ) with the custom where clause based on the user selection.

Which technology are you more familiar with? LINQ would be better, but I can give an answer in ADO.NET as well ( SqlConnection, SqlCommand , etc).

So the LINQ would be relatively simple. After setting up your LINQ to Entities (EDMX) or LINQ to SQL (DBML) (I'd do the EDMX, because L2S is no longer supported in forward maintenance by MSFT). With an existing DB, it's very easy, drag and drop.

The code would look like this:

using(var context = new LinqDbContext())
{
    var results = context.Tablename;
    if(limitByConfEmail)
    {
        results = results.Where(data => data.ConfirmationEmail == true);
    }
    // do your elses here

    gridview.DataSource = results;
    gridview.DataBind();
}

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