Can I then use datatable to handle the request below and how? - c#

public static double Evaluate(string expression)
{
System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("expression", string.Empty.GetType(), expression);
System.Data.DataRow row = table.NewRow();
table.Rows.Add(row);
return double.Parse((string)row["expression"]);
}
public void ProcessingRequest(Object obj)
{
int index = (Int32)obj;
while (true)
{
try
{
string str1 = socket[index].ReceiveData();
str1 = str1 + "\n";
textBox4.AppendText(str1);
double s = Evaluate(str1);
socket[index].SendData(s.ToString());
}
catch
{
socket[index].CloseSocket();
return;
}
}
}
How to copy the calculation lines in the textbox into a separate file then use those lines to check if it exists or not? if so, only send the result, otherwise, do the calculation. Can I use datatable and how?

Related

C# DataGridView virtual mode: Enable sorting

Is there a way to sort a DataGridView in virtual mode?
I have implemented a Gridview in virtual mode following this microsoft example: http://msdn.microsoft.com/de-de/library/ms171624.aspx . Also I have modified the example to be able to write data to database. This works out fine and the virtual mode gives a huge increase in speed, but my customer needs to sort the columns.
After searching the web for a while I found the Link http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/25b3f7c3-95b6-4c49-802b-b5a2a62915ac , but can´t get it to work.
Could anybody point out how if there is way to sort columns in virtual mode and if so, how I would have to do it?
Thanks a lot in advance!
Ok, I´ve solved this now. Using the microsoft example ( http://msdn.microsoft.com/de-de/library/ms171624.aspx ) I modified the DataRetrieverLog class to receive an additional value in the constructor: The column name to sort by (this includes the sort direction, e.g. "Name ASC"). For anyone interested, here´s the modified code:
public class DataRetrieverLog : IDataPageRetriever
{
private string tableName;
private string sortColumn;
private SqlCommand command;
private DataTable table;
private SqlDataAdapter adapter;
public DataRetrieverLog(string connectionString, string tableName, string sortColumn)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
command = connection.CreateCommand();
this.tableName = tableName;
this.sortColumn = sortColumn;
}
private int rowCountValue = -1;
public int RowCount
{
get
{
// Return the existing value if it has already been determined.
if (rowCountValue != -1)
{
return rowCountValue;
}
// Retrieve the row count from the database.
command.CommandText = "SELECT COUNT(*) FROM " + tableName;
rowCountValue = (int)command.ExecuteScalar();
return rowCountValue;
}
}
private DataColumnCollection columnsValue;
public DataColumnCollection Columns
{
get
{
// Return the existing value if it has already been determined.
if (columnsValue != null)
{
return columnsValue;
}
// Retrieve the column information from the database.
command.CommandText = "SELECT * FROM " + tableName;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.FillSchema(table, SchemaType.Source);
columnsValue = table.Columns;
return columnsValue;
}
}
private string commaSeparatedListOfColumnNamesValue = null;
private string CommaSeparatedListOfColumnNames
{
get
{
// Return the existing value if it has already been determined.
if (commaSeparatedListOfColumnNamesValue != null)
{
return commaSeparatedListOfColumnNamesValue;
}
// Store a list of column names for use in the
// SupplyPageOfData method.
System.Text.StringBuilder commaSeparatedColumnNames =
new System.Text.StringBuilder();
bool firstColumn = true;
foreach (DataColumn column in Columns)
{
if (!firstColumn)
{
commaSeparatedColumnNames.Append("], [");
}
else
{
commaSeparatedColumnNames.Append("[");
}
commaSeparatedColumnNames.Append(column.ColumnName);
firstColumn = false;
}
commaSeparatedColumnNames.Append("]");
commaSeparatedListOfColumnNamesValue =
commaSeparatedColumnNames.ToString();
return commaSeparatedListOfColumnNamesValue;
}
}
// Declare variables to be reused by the SupplyPageOfData method.
private string columnToSortBy;
public DataTable SupplyPageOfData(int lowerPageBoundary, int rowsPerPage)
{
// Store the name of the ID column. This column must contain unique
// values so the SQL below will work properly.
if (columnToSortBy == null)
{
columnToSortBy = this.Columns[0].ColumnName;
}
if (!this.Columns[columnToSortBy].Unique)
{
throw new InvalidOperationException(String.Format(
"Column {0} must contain unique values.", columnToSortBy));
}
// Retrieve the specified number of rows from the database, starting
// with the row specified by the lowerPageBoundary parameter.
String text = "Select Top " + rowsPerPage + " " +
CommaSeparatedListOfColumnNames + " From " + tableName +
" WHERE " + columnToSortBy + " NOT IN (SELECT TOP " +
lowerPageBoundary + " " + columnToSortBy + " From " +
tableName + " Order By " + sortColumn +
") Order By " + sortColumn;
command.CommandText = text;
adapter = new SqlDataAdapter(text, GUI.dictSettings["connectionString"]);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);
table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.Fill(table);
return table;
}
public DataTable getDataTable()
{
return table;
}
public SqlDataAdapter getAdapter()
{
return adapter;
}
}
In addition to that, I implemented the ColumnHeaderMouseClick-Event in my Gridview. In that I get the column name and the sort direction and then reload all underlying table data by creating a new DataRetrieverLog instance and passing the column name + sort direction. Next I just refresh the Gridview: gridView.Refresh()
Thats it.
EDIT (20.07.2015):
To make things a bit clearer, here´s the full way of getting a sortable DataGridView in Virtual Mode to work. It´s been a while since I was playing around with this, so I hope I can make it clear enough for you to get it working and haven´t missed out on anything. Three Helper classes are needed to get this to work:
IDataPageRetriever.cs:
using System.Data;
using System.Data.SqlClient;
namespace ASC.Code.Forms.Helper
{
public interface IDataPageRetriever
{
DataTable SupplyPageOfData(int lowerPageBoundary, int rowsPerPage);
SqlDataAdapter getAdapter();
}
}
CacheAll.cs:
using System.Data;
using System.Data.SqlClient;
namespace ASC.Code.Forms.Helper
{
public class CacheAll
{
private static int RowsPerPage;
// Represents one page of data.
public struct DataPage
{
public DataTable table;
public SqlDataAdapter adapter;
private int lowestIndexValue;
private int highestIndexValue;
public DataPage(DataTable table, SqlDataAdapter adapter, int rowIndex)
{
this.table = table;
this.adapter = adapter;
lowestIndexValue = MapToLowerBoundary(rowIndex);
highestIndexValue = MapToUpperBoundary(rowIndex);
System.Diagnostics.Debug.Assert(lowestIndexValue >= 0);
System.Diagnostics.Debug.Assert(highestIndexValue >= 0);
}
public int LowestIndex
{
get
{
return lowestIndexValue;
}
}
public int HighestIndex
{
get
{
return highestIndexValue;
}
}
public static int MapToLowerBoundary(int rowIndex)
{
// Return the lowest index of a page containing the given index.
return (rowIndex / RowsPerPage) * RowsPerPage;
}
private static int MapToUpperBoundary(int rowIndex)
{
// Return the highest index of a page containing the given index.
return MapToLowerBoundary(rowIndex) + RowsPerPage - 1;
}
public DataTable getTable()
{
return this.table;
}
public SqlDataAdapter getAdapter()
{
return this.adapter;
}
}
private DataPage[] cachePages;
private IDataPageRetrieverAll dataSupply;
public CacheAll(IDataPageRetrieverAll dataSupplier, int rowsPerPage)
{
dataSupply = dataSupplier;
CacheAll.RowsPerPage = rowsPerPage;
LoadFirstTwoPages();
}
// Sets the value of the element parameter if the value is in the cache.
private bool IfPageCached_ThenSetElement(int rowIndex,
int columnIndex, ref string element)
{
if (IsRowCachedInPage(0, rowIndex))
{
element = cachePages[0].table
.Rows[rowIndex % RowsPerPage][columnIndex].ToString();
return true;
}
else if (cachePages.Length > 1)
{
if (IsRowCachedInPage(1, rowIndex))
{
element = cachePages[1].table.Rows[rowIndex % RowsPerPage][columnIndex].ToString();
return true;
}
}
return false;
}
public string RetrieveElement(int rowIndex, int columnIndex)
{
string element = null;
if (IfPageCached_ThenSetElement(rowIndex, columnIndex, ref element))
{
return element;
}
else
{
return RetrieveData_CacheIt_ThenReturnElement(
rowIndex, columnIndex);
}
}
private void LoadFirstTwoPages()
{
DataTable table1 = dataSupply.SupplyPageOfData(DataPage.MapToLowerBoundary(0), RowsPerPage);
SqlDataAdapter adapter1 = dataSupply.getAdapter();
DataTable table2 = dataSupply.SupplyPageOfData(DataPage.MapToLowerBoundary(RowsPerPage), RowsPerPage);
SqlDataAdapter adapter2 = dataSupply.getAdapter();
cachePages = new DataPage[]{
new DataPage(table1, adapter1, 0),
new DataPage(table2, adapter2, RowsPerPage)};
}
private string RetrieveData_CacheIt_ThenReturnElement(
int rowIndex, int columnIndex)
{
// Retrieve a page worth of data containing the requested value.
DataTable table = dataSupply.SupplyPageOfData(
DataPage.MapToLowerBoundary(rowIndex), RowsPerPage);
SqlDataAdapter adapter = dataSupply.getAdapter();
// Replace the cached page furthest from the requested cell
// with a new page containing the newly retrieved data.
cachePages[GetIndexToUnusedPage(rowIndex)] = new DataPage(table, adapter, rowIndex);
return RetrieveElement(rowIndex, columnIndex);
}
// Returns the index of the cached page most distant from the given index
// and therefore least likely to be reused.
private int GetIndexToUnusedPage(int rowIndex)
{
if (rowIndex > cachePages[0].HighestIndex &&
rowIndex > cachePages[1].HighestIndex)
{
int offsetFromPage0 = rowIndex - cachePages[0].HighestIndex;
int offsetFromPage1 = rowIndex - cachePages[1].HighestIndex;
if (offsetFromPage0 < offsetFromPage1)
{
return 1;
}
return 0;
}
else
{
int offsetFromPage0 = cachePages[0].LowestIndex - rowIndex;
int offsetFromPage1 = cachePages[1].LowestIndex - rowIndex;
if (offsetFromPage0 < offsetFromPage1)
{
return 1;
}
return 0;
}
}
// Returns a value indicating whether the given row index is contained
// in the given DataPage.
private bool IsRowCachedInPage(int pageNumber, int rowIndex)
{
return rowIndex <= cachePages[pageNumber].HighestIndex &&
rowIndex >= cachePages[pageNumber].LowestIndex;
}
public DataPage[] getCachePages()
{
return cachePages;
}
}
}
…and the DataRetrieverAll.cs class:
using System;
using System.Data.SqlClient;
using System.Data;
namespace ASC.Code.Forms.Helper
{
public class DataRetrieverAll : IDataPageRetrieverAll
{
private string tableName;
private string sortColumn;
private SqlCommand command;
private DataTable table;
private SqlDataAdapter adapter;
public DataRetrieverAll(string connectionString, string tableName, string sortColumn)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
command = connection.CreateCommand();
this.tableName = tableName;
this.sortColumn = sortColumn;
}
private int rowCountValue = -1;
public int RowCount
{
get
{
// Return the existing value if it has already been determined.
if (rowCountValue != -1)
{
return rowCountValue;
}
// Retrieve the row count from the database.
command.CommandText = "SELECT COUNT(*) FROM " + tableName;
rowCountValue = (int)command.ExecuteScalar();
return rowCountValue;
}
}
private DataColumnCollection columnsValue;
public DataColumnCollection Columns
{
get
{
// Return the existing value if it has already been determined.
if (columnsValue != null)
{
return columnsValue;
}
// Retrieve the column information from the database.
command.CommandText = "SELECT * FROM " + tableName;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.FillSchema(table, SchemaType.Source);
columnsValue = table.Columns;
return columnsValue;
}
}
private string commaSeparatedListOfColumnNamesValue = null;
private string CommaSeparatedListOfColumnNames
{
get
{
// Return the existing value if it has already been determined.
if (commaSeparatedListOfColumnNamesValue != null)
{
return commaSeparatedListOfColumnNamesValue;
}
// Store a list of column names for use in the
// SupplyPageOfData method.
System.Text.StringBuilder commaSeparatedColumnNames =
new System.Text.StringBuilder();
bool firstColumn = true;
foreach (DataColumn column in Columns)
{
if (!firstColumn)
{
commaSeparatedColumnNames.Append("], [");
}
else
{
commaSeparatedColumnNames.Append("[");
}
commaSeparatedColumnNames.Append(column.ColumnName);
firstColumn = false;
}
commaSeparatedColumnNames.Append("]");
commaSeparatedListOfColumnNamesValue =
commaSeparatedColumnNames.ToString();
return commaSeparatedListOfColumnNamesValue;
}
}
// Declare variables to be reused by the SupplyPageOfData method.
private string columnToSortBy;
public DataTable SupplyPageOfData(int lowerPageBoundary, int rowsPerPage)
{
// Store the name of the ID column. This column must contain unique
// values so the SQL below will work properly.
if (columnToSortBy == null)
{
columnToSortBy = this.Columns[0].ColumnName;
}
if (!this.Columns[columnToSortBy].Unique)
{
throw new InvalidOperationException(String.Format(
"Column {0} must contain unique values.", columnToSortBy));
}
// Retrieve the specified number of rows from the database, starting
// with the row specified by the lowerPageBoundary parameter.
String text = "Select Top " + rowsPerPage + " " +
CommaSeparatedListOfColumnNames + " From " + tableName +
" WHERE " + columnToSortBy + " NOT IN (SELECT TOP " +
lowerPageBoundary + " " + columnToSortBy + " From " +
tableName + " Order By " + sortColumn +
") Order By " + sortColumn;
command.CommandText = text;
adapter = new SqlDataAdapter(text, GUI.dictSettings["connectionString"]);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);
table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.Fill(table);
return table;
}
public DataTable getDataTable()
{
return table;
}
public SqlDataAdapter getAdapter()
{
return adapter;
}
}
}
So, how do I fill the Grid? I use another Helper-Class and call a method within the Helper-Class from the Main GUI- class:
Main.cs:
//...
private String columnToSortByAll;
public GUI()
{
InitializeComponent();
init();
}
private void init()
{
helper = new GUIHelper(grid, this);
//Tabellen mit Werten füllen
fillTablesInit();
}
private void fillTablesInit()
{
helper.getData("(SELECT * FROM TOOL_materialSumme WHERE Display IS NULL OR Display = 1)a", "ID", asc_all); //asc_all = Boolean value, indicating sort direction asc /desc
}
private void grid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
String columnName = grid.Columns[e.ColumnIndex].Name;
if (columnName.Equals(columnToSortBy))
{
if (asc_all) asc_all = false; else asc_all = true;
}
else
{
columnToSortBy = columnName;
asc_all = true;
}
helper.getDataALL("(SELECT * FROM TOOL_materialSumme WHERE Display IS NULL OR Display = 1)a", columnToSortBy, asc_all);
}
private void grid_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
String actualValue = helper.getMemoryCache().RetrieveElement(e.RowIndex, e.ColumnIndex);
e.Value = actualValue;
}
private void grid_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
//MessageBox.Show(e.Context.ToString());
}
private void grid_CellValuePushed(object sender, DataGridViewCellValueEventArgs e)
{
String newValue = "";
if (e.Value != null) newValue = e.Value.ToString();
int column = e.ColumnIndex;
ASC.Code.Forms.Helper.CacheAll.DataPage[] pages = helper.getMemoryCache().getCachePages();
DataTable[] tables = new DataTable[2];
SqlDataAdapter[] adapters = new SqlDataAdapter[2];
tables[0] = pages[0].getTable();
tables[1] = pages[1].getTable();
adapters[0] = pages[0].getAdapter();
adapters[1] = pages[1].getAdapter();
String id = grid.Rows[e.RowIndex].Cells["ID"].Value.ToString();
for (int x = 0; x < tables.Length; x++)
{
for (int a = 0; a < tables[x].Rows.Count; a++)
{
String temp = tables[x].Rows[a][column].ToString();
if (tables[x].Rows[a]["ID"].ToString() == id)
{
tables[x].Rows[a][column] = newValue;
adapters[x].Update(tables[x]);
break;
}
}
}
grid.Refresh();
}
//...
GUIHelper.cs:
private DataGridView grid
private CacheAll memoryCache;
private DataRetrieverAll retriever;
public GUIHelper(DataGridView grid, GUI gui)
{
this.gui = gui;
this.grid = grid;
init();
}
private void init()
{
//...
}
public void getData(string selectCommand, string sortColumn, Boolean asc_all)
{
grid.VirtualMode = true;
try
{
if (asc_all) sortColumn = "["+sortColumn + "] ASC"; else sortColumn = "["+sortColumn + "] DESC";
retriever = new DataRetrieverAll("Insert ConnectionString here...", selectCommand, sortColumn);
memoryCache = new CacheAll(retriever, GUI.amountDatasets); //amountDatasets = Amount of Datasets per cached-page
if (grid.Columns.Count == 0)
{
foreach (DataColumn column in retriever.Columns)
{
grid.Columns.Add(column.ColumnName, column.ColumnName);
}
}
grid.Rows.Clear();
grid.RowCount = retriever.RowCount;
grid.Refresh();
}
catch (SqlException)
{
MessageBox.Show("Connection could not be established. " +
"Verify that the connection string is valid.");
Application.Exit();
}
}
public CacheAll getMemoryCache()
{
return memoryCacheAll;
}
Well, that´s the way I did it and it worked out well. I ended up not using it, but still have the code... It´s important to set grid.VirtualMode = true and to implement the ColumnHeaderMouseClick event for the grid in the Main class. Happy coding :-)

is it the recursive function being triggered in C#

I have called a function inside a function. However, I found the function GetExpression() inside the Calculate() function is run many times. It seems some loop is run or recursive is run. I cannot figure out how it is being run many times, not sure how it is being loop or recursive. I found in application log, that the GetExpression is run many times when the Calculate funtions is run. Am I missing some information to find out how it is being loop? Please help.
public DataSet Calculate(int compID, DateTime? fromDate, DateTime? toDate, string indiIDs)
{
bool allowGetting = true;
DataSet results = null;
try
{
string unit = null;
bool isEnabled = IsResultsEnabled(comID);
if (isCalResultEnabled)
{
unit = GetUnit(comID, indicatorIDs, callerAcceptedUnit);
results = CheckResults(comID, indicatorIDs, unit);
EnsureUpToDate(comID, results);
if (calculatedResults.Tables[0].Rows.Count > 0)
{
allowGetting = false;
}
}
if (!allowGetting && results != null)
{
DataSet ds = GenerateResults(results);
return ds;
}
else
{
string expression = GetExpression(compID, fromDate, toDate, indiIDs);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
dt.Columns.Add("Expression");
dt.Columns.Add("Result", Type.GetType("System.Decimal"));
DataRow newRow = dt.NewRow();
newRow["Expression"] = expression;
if (string.IsNullOrWhiteSpace(expression))
{
newRow["Result"] = DBNull.Value;
}
else
{
if (expression.EndsWith("+"))
{
expression = expression.Substring(0, expression.Length - 1);
}
object result = null;
try
{
result = dt.Compute(expression, "");
newRow["Result"] = Convert.ToDecimal(result);
}
catch (Exception ex)
{
Logger.Log(string.Format("Error occurs");
throw;
}
}
dt.Rows.Add(newRow);
return ds;
}
}
catch
{
throw;
}
finally
{
if (results != null)
{
results.Dispose();
results = null;
}
}
}

Integer List not getting converted to Datatable C#

I want to convert a List to a Datatable. I am using the following code :
public static DataTable ConvertToDataTable(object o)
{
DataTable dt = new DataTable("OutputData");
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
o.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
f.GetValue(o, null);
dt.Columns.Add(f.Name, f.PropertyType);
dt.Rows[0][f.Name] = f.GetValue(o, null);
}
catch { }
});
return dt;
}
The following is the class object that I am trying to pass to the ConverToDataTable method :
public class Class1
{
private List<int> _intList;
public List<int> intList
{
get
{
return _intList;
}
set
{
_intList = value;
}
}
}
But when I am trying to convert the class1 object to DataTable I am getting the datatable columns as count and Capacity.. What am I doing wrong?
If you want to convert an integer list to Datatable you do not need to use Reflection. This can be solution.
public DataTable ConvertToDataTable(List<int> o)
{
DataTable dt = new DataTable("OutputData");
dt.Columns.Add("Integers", Type.GetType("System.Int32"));
foreach (var item in o)
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
dt.Rows[dt.Rows.Count - 1][0] = item;
}
return dt;
}
But if you want to convert an object list to a datatable, then you have to use reflection.
of course because you are adding the list value not the integer values inside the list see this

print problem with rdlc

I am going to create print page in wpf with *.rdlc.
For this , i create a class(following is this codes).
I bind the class to report but when i run the program , following message occurs :
A data source instant has not been supplied for data source 'dataset1'
class rpt_insurance
{
private string _insurance;
private int _count_print;
private int _sum_tariff;
private int _lot_org;
public string insurance
{
get { return _insurance; }
set { _insurance = value; }
}
public int count_print
{
get { return _count_print; }
set { _count_print = value; }
}
public int sum_tariff
{
get { return _sum_tariff; }
set { _sum_tariff = value; }
}
public int lot_org
{
get { return _lot_org; }
set { _lot_org = value; }
}
public DataTable report_insurance(string from_date,string to_date)
{
using (doctorEntities de = new doctorEntities())
{
var print = (from Table_infobase_print tip in de.Table_infobase_print
where tip.Print_date.CompareTo(from_date) > 0 && tip.Print_date.CompareTo(to_date) < 0
select tip).ToList();
var insurance = (from Table_insurance_org tio in de.Table_insurance_org
select tio).ToList();
List<rpt_insurance> lri = new List<rpt_insurance>();
foreach (var insurance_row in insurance)
{
rpt_insurance ri = new rpt_insurance();
int number = 0;
foreach (var print_row in print)
{
if(print_row.insurance_org==insurance_row.org_name)
{
number++;
ri.insurance = print_row.insurance_org;
ri.count_print = number;
ri.sum_tariff = ri.sum_tariff + print_row.sum_tariff;
ri.lot_org=lot_org+(print_row.sum_tariff-print_row.sum_lot_patient);
}
}
if (ri.insurance != null)
{
lri.Add(ri);
}
}
DataTable dt = new DataTable();
dt = new DataTable();
dt.Columns.Add("cinsurance");
dt.Columns.Add("ccount_print");
dt.Columns.Add("csum_tariff");
dt.Columns.Add("clot_org");
for (int i = 0; i < lri.Count; i++)
{
DataRow dr = dt.NewRow();
dr["cinsurance"] = lri[i].insurance;
dr["ccount_print"] = lri[i].count_print;
dr["csum_tariff"] = lri[i].sum_tariff;
dr["clot_org"] = lri[i].lot_org;
dt.Rows.Add(dr);
}
return dt;
}
}
}
You need to supply the dataset to your report. Something like:
viewer.LocalReport.DataSources.Add(new ReportDataSource("dataset1", dataTable));
Edit: based on your comment
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var dataTable = report_insurance(fromDate, toDate);
viewer_insurance.LocalReport.ReportPath = "E:\\desktop\\Doctor\\Project\\Doctor\\Doctor\\rinsurance.rdlc";
viewer_insurance.LocalReport.DataSources.Add(new ReportDataSource("dataset1", dataTable);
viewer_insurance.RefreshReport();
}
You really can't get around the need to call your data retrieval method AND send that data through to the report.

.net How can set the anonymous type for IEnumberable

I need to Convert a Ienumerable to a dataset. For this i need to write a common fnction to convert any IEnumberable type to Dataset. For this I need to set anonymous type.
Here is the Code
public static DataTable ToDataTable(Object alist)
{
String AssemblyName = "DataAccessLayer";
String ClassName = "sptblSystemPreference_GetListResult";
Type ObjType = Type.GetType(ClassName + "," + AssemblyName);
//Below line working fine... But how can i implement ObjType in the IEnumberable
IEnumerable<DataAccessLayer.sptblSystemPreference_GetListResult> objList1 = (IEnumerable<DataAccessLayer.sptblSystemPreference_GetListResult>)alist;
List<DataAccessLayer.sptblSystemPreference_GetListResult> objList = objList1.ToList();
DataTable dt = new DataTable();
if (objList[0] != null)
{
dt.TableName = objList[0].GetType().Name;
System.Reflection.PropertyInfo[] propInfo = objList[0].GetType().GetProperties();
for (int PropertyCount = 0; PropertyCount < propInfo.Length; PropertyCount++)
{
dt.Columns.Add(propInfo[PropertyCount].Name);
}
for (int row = 0; row < objList.Count; row++)
{
DataRow dr;
dr = dt.NewRow();
for (int PropertyCount = 0; PropertyCount < propInfo.Length; PropertyCount++)
{
Object obj = propInfo[PropertyCount].GetValue(objList[row], null);
if(obj!=null)
dr[PropertyCount] = obj;
}
dt.Rows.Add(dr);
}
}
return dt;
}
}
I implemented this to convert a IList<T> to a DataTable and documented it on my blog:
public static class ListExtensions
{
public static DataTable ToDataTable<T>(this IList<T> list)
{
IList<PropertyInfo> properties = list.GetPropertiesOfObjectInList();
DataTable resultTable = CreateTable(properties);
foreach(var item in list)
{
var row = CreateRowFromItem<T>(resultTable, item);
resultTable.Rows.Add(row);
}
return resultTable;
}
private static DataTable CreateTable(IList<PropertyInfo> properties)
{
DataTable resultTable = new DataTable();
foreach (var property in properties)
{
resultTable.Columns.Add(property.Name, property.PropertyType);
}
return resultTable;
}
public static IList<PropertyInfo> GetPropertiesOfObjectInList<T>(this IList<T> list)
{
return typeof(T).GetProperties().ToList();
}
private static DataRow CreateRowFromItem<T>(DataTable resultTable, T item)
{
var row = resultTable.NewRow();
var properties = item.GetType().GetProperties().ToList();
foreach (var property in properties)
{
row[property.Name] = property.GetValue(item, null);
}
return row;
}
}
This allows you to write code like DataTable yourTable = yourList.ToDataTable(). You can read about it here: Generic list to DataTable

Resources