Data formatting in GridView with AutoGenerateColumns true - asp.net

I've got a GridView in ASP.NET 2.0 with AutoGenerateColumns set to true. It'll be bound at runtime to a DataSet with one of many possible schemas, and I'd rather not set up grids and columns for each possible schema.
Some of the columns in the grid will sometimes be floating point values. It seems the default number formatting turns 0.345 into 0.345000. Is there a way to change the default number format so it trims to a set number of decimals?

You could use strings in your schema instead of floating point for display purposes, and perform the formatting manually, something like this:
EDIT: Without LINQ, you can do the same thing by modifying rows in the schema:
// load source data
DataSet myData = GetDataSet();
// create column for formatted data.
myData.Tables["MyTable"].Columns.Add("AmountFormatted", typeof(string));
// apply formatting
foreach (DataRow dr in myData.Tables["MyTable"].Rows)
dr["AmountFormatted"] = string.Format("{0:0.###}", dr["Amount"]);
// remove source column and replace with formatted column
myData.Tables["MyTable"].Columns.Remove("Amount");
myData.Tables["MyTable"].Columns["AmountFormatted"].ColumnName = "Amount";
C#, LINQ-Based solution:
var theData = GetDataSchema1();
var dataSource = theData.Tables["MyTable"].Select().Select(dr =>
new { /* select only columns you want displayed, and apply formatting */
MyColumn1 = dr["MyColumn1"],
MyColumn2 = dr["MyColumn2"],
MyColumn3 = String.format("#.###", dr["MyColumn3"]),
MyColumn4 = dr["MyColumn4"],
MyColumn5 = dr["MyColumn5"]
}
);
MyGridView1.DataSource = dataSource;
MyGridView1.DataBind()

Related

itextsharp leaving first page empty and printing table conent in following table

I have three part in my PDF generating document using iTextSharp library.
The Header and footer I am printing using OnEndPage() of PdfPageEventHelper class. The header and footer printing well in all pages.But problem in printing large table content from middle of the page.
Now, I am facing problem when I have more that 100 table rows content to print on middle of the page.
On first page (middle of the page) I am printing table with more than 100 rows, but in this case it leave the first page empty and start printing table content on second page. Here is my table that I am trying to print on first page
PdfPTable table = new PdfPTable(5);
table.HeaderRows = 1;
table.SplitLate = false;
table.SplitRows = false;
table.SetTotalWidth(new float[] { 100, 75, 75, 75, 75 });
table.LockedWidth = true;
for (int i = 0; i < 150; i++)
{
PdfPCell cell = new PdfPCell(new phrase());
cell.Colspan = 5;
table.AddCell(cell);
}
I am using iTextSharp version: 5.4.5.0
Is there any configuration need to do, that will prevent page break?
But I am getting actual result in this format
Allow me to comment on these two lines:
table.SplitLate = false;
table.SplitRows = false;
The first line tells iTextSharp what it should do if a row doesn't fit a page. If you set this value to false, rows will be split late. For instance: you have a big row that doesn't fit the current page. In that case, the row will be forwarded to the next page. If it still doesn't fit the page, then another decision needs to be made: should the row be split or not?
The second line gives iTextSharp the answer to that question. If the value of SplitRows is true, then the row will be split. If the value is false, the row will be dropped. Allow me to quote the official documentation (p115 of "iText in Action - Second Edition"):
Ths is a dangerous line, because now not one row will be split. Rows that are too high to fit on a page will be dropped from the table!
I have the feeling that you want all the rows to show up in the table, so I suggest that you change the two lines I mentioned to:
table.SplitLate = true;
table.SplitRows = true;
Actually: why don't you just remove those two lines? The default value of SplitLate and of SplitRows is true.
Same thing happened to me using nested tables.
I solved this problem using .SplitLate = false; in the first table :)

Why is the cell data duplicated in each column?

I'm new to PHPExcel and somehow I got the same data duplicated in the Excel spreadsheet using the following code:
<?php
$roster_sql = "SELECT * FROM EMPLOYEE";
$roster_result = mysql_query($roster_sql) or die(mysql_error());
// Populate 2D Array
$kcount = 0;
while($sheet_array = mysql_fetch_array($roster_result))
{
$sheet[$kcount] = $sheet_array;
$kcount++;
}
$rowID = 1;
foreach($sheet as $rowArray)
{
$columnID = 'A';
foreach($rowArray as $columnValue)
{
$objPHPExcel->getActiveSheet()->setCellValue($columnID.$rowID, $columnValue);
$columnID++;
}
$rowID++;
}
?>
The generated spreadsheet has each cell value duplicated in the column. Did I populate the array incorrectly or is there something wrong when I write out the array?
Further, how do I write the header row in the same spreadsheet without hard coding the column names from the SQL?
Thanks for your help.
Default behaviour for mysql_fetch_array() is to return an array with both enumerated and associative values for each column. i.e. the $result_type argument is MYSQL_BOTH.
If you only want either an associative or an enumerated result (but not both), then you need to specify this, e.g.
while($sheet_array = mysql_fetch_array($roster_result, MYSQL_ASSOC))
or
while($sheet_array = mysql_fetch_array($roster_result, MYSQL_NUM))
or use one of the related functions, e.g.
while($sheet_array = mysql_fetch_assoc($roster_result))
or
while($sheet_array = mysql_fetch_row($roster_result))
EDIT
If you want to write out the column names as a header, then you need to call something like mysql_list_fields() to get the list of columns for the table
Or alternatively, retrieve your data as an associative array, and then the key values will be your column names

Formatting Data in DataSet

I created a data set from an xml file and attached it to a gridview. I would like to do how do i format the data in the dataset or from the gridview, for example, change the header text for a column or also show only certain items in my gridview.
Dim xmlDataSet As New DataSet
xmlDataSet.ReadXml(GlobalClass.GlobalUrl)
GridView1.DataSource = xmlDataSet
GridView1.DataBind()
Is there anyway how to go about manipulating the data inside a dataset? Thank you.
You can try with theses posts :
First definition : http://msdn.microsoft.com/en-us/library/zb0sdh0b.aspx
Note : it's very interessant to read theses links about methods and properties
link 1 : http://msdn.microsoft.com/fr-fr/library/system.data.dataset.aspx
link 2 : http://msdn.microsoft.com/fr-fr/library/system.data.dataset.tables.aspx
You can do this for renaming columns:
xmlDataSet.Tables[0].Columns["CurrentColumnName"].ColumnName = "NewColumnName";
Here is a way to hide or show columns:
xmlDataSet.Tables[0].Columns["ColumnName"].Visible = true;

Bind Values to GridView

I have a List with following values
List<Calculations> calcs = new List<Calculations>();
Calculations cal = new Calculations();
cal.TotalTotalC2 = Convert.ToInt32(reader["TotalTotalC2"].ToString());
cal.TotalTotalC3 = Convert.ToInt32(reader["TotalTotalC3"].ToString());
cal.TotalC1C4IOM = Convert.ToInt32(reader["TotalC1C4IOM"].ToString());
cal.TotalC1C4MDR = Convert.ToInt32(reader["TotalC1C4MDR"].ToString());
calcs.Add(cal);
i need to Bind these Numeric values in the following table format.left hand side plain text and right hand side the bound values.
Can some one plz tell me that how can i use GridView to bind in above format.
you have to write code in RowDataBound event , and check for row number in each iteration and based on the row number bind the column text of your custom list to the column, I don't think there is any auto function to bind column names to grid!!! let me know if you find something direct and easy
I had to dynamically generate a DataTable and then bind it to GridView
DataTable dt=new DataTable();
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Count", typeof(int));
foreach (Calculations item in calcs )
{
dt.Rows.Add("Total ...", item.TotalTotalC2);
dt.Rows.Add("Total ...", item.TotalTotalC3);
}

Flex - sorting a datagrid column by the row's label

I'm creating a table that displays information from a MySQL database, I'm using foreignkeys all over the place to cross-reference data.
Basically I have a datagrid with a column named 'system.' The system is an int that represents the id of an object in another table. I've used lableFunction to cross-reference the two and rename the column. But now sorting doesn't work, I understand that you have to create a custom sorting function. I have tried cross-referencing the two tables again, but that takes ~30sec to sort 1200 rows. Now I'm just clueless as to what I should try next.
Is there any way to access the columns field label inside the sort function?
public function order(a:Object,b:Object):int
{
var v1:String = a.sys;
var v2:String = b.sys;
if ( v1 < v2 ){
trace(-1);
return -1;
}else if ( v1 > v2 ){
trace(1);
return 1;
}else {
trace(0);
return 0;
}
}
One way to handle this is to go through the objects you received and add the label as a property on each of them based on the cross-referenced id. Then you can specify your label property to display in your data grid column instead of using a label function. That way you would get sorting as you'd expect rather than having to create your own sort function.
The way that DataGrids, and other list based classes work is by using itemRenderers. Renderers are only created for the data that is shown on screen. In most cases there is a lot more data in your dataProvider than what is seen on screen.
Trying to sort your data based on something displayed by the dataGrid will most likely not give you the results you want.
But, there is no reason you can't call the same label function on your data objects in the sortFunction.
One way is to use the itemToLabel function of the dataGrid:
var v1:String = dataGrid.itemToLabel(a);
var v2:String = dataGrid.itemToLabel(b);
A second way is to just call the labelFunction explicitly:
var v1:String = labelFunction(a);
var v2:String = = labelFunction(b);
In my experience I have found sorting to be extremely quick, however you're recordset is slightly larger than what I usually load in memory at a single time.

Resources