简体   繁体   中英

How to Change Column Name In DataReader In C#?

I have SqlDataReader that gets returned from a ExecuteDataReader statement.

All I want is: change some column name in the data reader, just before binding to grid.

Here's the situation:

  1. First I build the structure Of grid (structure is in the table in database that was filled based on the output of a stored procedure in the system in the past)
  2. I execute data reader to execute stored procedure
  3. Binding the data reader to the grid

Here is the problem: if one column in the stored procedure is in upper case and related column in the grid is in lower case, the grid does not fill.

And I have a lot of stored procedures based on this architecture. Some of them have many rows to display. And because of that I use data reader for performance.

  1. I don't want to change the column name in the stored procedure (too much work)
  2. I don't want to copy the result of data reader to another data holder (because of overhead, and low performance)
  3. I just one way to change the column name of the data reader

    sqlDataReader reader; reader.executedatareadet();

For example after data reader is returned I have two columns ( A,B ).

I want to change column 'A' to 'a' (convert to lower case) before binding it to the grid like reader.GetName(i)

I want to be able to do something like

reader.SetName(i)

but it seams that we cant change the data reader column name

  1. You can change the column names in GridView
  2. If possible alter the Stored Procedure with new column names

您可以尝试使用预定义的列名称在DataTable中加载DbDataReader,然后在tout应用程序中将该表用作数据源。

My recommendation here would be: separate the UI and database code. If your UI is affected by a data-reader, then that simply makes me ask: "why is the UI talking to a data-reader?". Those two things are at total opposite ends of the stack. I would abstract that by having your DAL return a concrete list of populated POCO/DTO types (or possibly view-model types), ie

public List<Customer> GetCustomers({some filter etc}) {...}

then bind to that , ie

var customers = dal.GetCustomers(...);
...
someUI.DataSource = customers;

The Customer type is then well defined with properties such as:

public class Customer {
    public int Id {get;set;}
    public string Name {get;set;}
    ...
}

Any implementation changes at the DAL are now completely separated from the UI.

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