I have aa table TBL_Person
with five columns :
Person_ID, FirstName, LastName, Age, Location
and I have a method which returns a dataset:
public DataSet GetPerson()
{
SqlCommand _select = new SqlCommand();
_select.CommandText = "SP-GetAllPerson";
_select.CommandType = System.Data.CommandType.StoredProcedure;
_select.Connection = Connection.GetConnection;
SqlDataAdapter _daPerson = new SqlDataAdapter(_select);
DataSet _personDs = new DataSet();
_daCountry.Fill(_personDs, "[TBL_Person]");
return _personDs;
}
This method will return a dataset with columns:
Person_ID, FirstName, LastName, Age, Location
but I want my method return a dataset with these columns:
FirstName, LastName, Age
How can I do it?
Change your stored-procedure accordingly if you don't want to select all columns.
If you want to change it in C# you can remove unwanted columns via table.Columns.Remove(name)
:
public DataSet GetPerson(IEnumerable<string> wantedColumns)
{
using(SqlConnection connection = new SqlConnection("Connection-String"))
using (SqlDataAdapter _daPerson = new SqlDataAdapter("SP-GetAllPerson", connection))
{
_daPerson.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
DataSet _personDs = new DataSet();
_daPerson.Fill(_personDs, "TBL_Person");
DataTable tblPersonIds = _personDs.Tables["TBL_Person"];
var allColumns = tblPersonIds.Columns.Cast<DataColumn>().Select(c => c.ColumnName);
// remove unwanted columns:
foreach (string columnToRemove in allColumns.Except(wantedColumns))
tblPersonIds.Columns.Remove(columnToRemove);
return _personDs;
}
}
You call this method in this way:
DataSet dsPerson = GetPerson(new[]{"FirstName", "LastName", "Age"});
If you don`t want to change your SP in data base then change your GetPerson() method in your .cs file like that:
public DataSet GetPerson()
{
SqlCommand _select = new SqlCommand();
_select.CommandText = "SP-GetAllPerson";
_select.CommandType = System.Data.CommandType.StoredProcedure;
_select.Connection = Connection.GetConnection;
SqlDataAdapter _daPerson = new SqlDataAdapter(_select);
DataSet _personDs = new DataSet();
_daPerson.Fill(_personDs, "[TBL_Person]");
_personDs.Tables["TBL_Person"].Columns.Remove("Person_ID");
_personDs.Tables["TBL_Person"].Columns.Remove("Location");
return _personDs;
}
Otherwise you can change your stored procedure accordingly.
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.