customizing the auto generated grid view in asp.net/c# - asp.net

I'm creating a column through ItemTemplate in my gridview, how can i adjust it to be my last column, unfortunately .net is making this column to be the first in grid view i want it to be the last column. The rest of the columns are automatically created by this code.
I mean
gridview1.datasource = myArrayList
gridview1.databind()
Please help me
Thanks in anticipation

Don't use the auto generation feature (AutoGenerateColumns="false") and supply the columns in the <columns> collection of the grid, or use LINQ:
var list = new List<MyClass>
{
new MyClass { Name = "A", Value = 1, Key = 1 }
};
gridView1.datasource = list.Select(i => new
{
i.Key,
i.Name,
i.Value
});
THe first option will be better on performance.

Related

Devexpress - Re-bind Chart Control error Index was out of range

I has using dexexpress chartcontrol and bind the datasource in runtime.
chartControl1.DataSource = ds.Tables[0];
chartControl1.SeriesDataMember = "Task";
chartControl1.SeriesTemplate.ArgumentDataMember = "Resource";
chartControl1.SeriesTemplate.ValueDataMembers.AddRange(new string[] { "Percentage" });
chartControl1.SeriesTemplate.View = new StackedBarSeriesView();
The first time binding, it has work fine and can show the chart.
When I click a button to re-create the dataset with new row of data, it give me an error in
chartControl1.DataSource = ds.Tables[0];
I has set the dataset = new dataset before fill it again with new data.
Any one has idea what wrong. Please help.
You should be able to do something along the lines of the following:
this.chartControl1.BeginInit();
DataTable chartData = this.chartControl1.DataSource as DataTable;
DataRow row = new DataRow()
{
"col1",
"col2"
}
chartData.Rows.Add(row);
this.chartControl1.RefreshData();
this.chartControl1.EndInit();
I hope this is helpful.
I have found that DevExpress occasionally gets confused when I set the DataSource, especially to an existing object. To work round this, before I set the DataSource to anything, I always set it to null first. Since doing that, I have not had any problems.
Give that a try.

Flex 3: dynamically created checkbox column in datagrid - data population issues and event listener

I have a datagrid control in my mxml file:
Now in my AS file, in the result function when obtaining data from DB, I can create columns dynamically. Let's say I create 1 column (client name):
private function GetDebtors_Result(event:ResultEvent):void
{
var arrayCol:Array = new Array();
var xmlSrc:XML = new XML("<main></main>");
var xmlTmp:XML;
var colClientname:DataGridColumn;
//Build an XML from DB data received (could as well use "event.result" directly to act as dataprovider for the datagrid, but I needed to break it down here)
for each(var o:Object in event.result)
{
xmlTmp = <row>
<CLIENTNAME>{o.CLIENTNAME}</CLIENTNAME>
</row>;
xmlSrc.appendChild(xmlTmp);
}
//Create the column CLIENTNAME
colClientname = new DataGridColumn("CLIENTNAME");
colClientname.headerText = "Client Name";
//Add the newly created column in the "Column" array.
arrayCol.push(colClientname);
//Use the "Column" array to set the columns of the datagrid.
dgSearch.columns = arrayCol;
//Populate the datagrid with the XML data.
dgSearch.dataProvider = xmlSrc.row;
}
This works well.
Now comes the issue: I need to add a second column which will contain checkboxes. They will be selected or deselected depending on the data from database. I'll show how I've done it by updating the same "GetDebtors_Result" function as above (added lines are commented as "// ADDED"):
private function GetDebtors_Result(event:ResultEvent):void
{
var arrayCol:Array = new Array();
var xmlSrc:XML = new XML("<main></main>");
var xmlTmp:XML;
var colClientname:DataGridColumn;
var colSel:DataGridColumn; // **ADDED**
//Build an XML from DB data received (could as well use "event.result" directly to act as dataprovider for the datagrid, but I needed to break it down here)
for each(var o:Object in event.result)
{
xmlTmp = <row>
<CLIENTNAME>{o.CLIENTNAME}</CLIENTNAME>
<SELECTED>{(o.SELECTED == 1)?true:false}</SELECTED> //**ADDED**
</row>;
xmlSrc.appendChild(xmlTmp);
}
//Create the column CLIENTNAME
colClientname = new DataGridColumn("CLIENTNAME");
colClientname.headerText = "Client Name";
//Create the column SELECTED
colSel = new DataGridColumn("SELECTED"); // **ADDED**
colSel.headerText = ""; // **ADDED**
colSel.itemRenderer = new ClassFactory(mx.controls.CheckBox); // **ADDED**
colSel.dataField = "SELECTED"; // **ADDED**
//Add the newly created column in the "Column" array.
arrayCol.push(colClientname);
//Add the "selection" column in the "Column" array.
arrayCol.push(colSel); // **ADDED**
//Use the "Column" array to set the columns of the datagrid.
dgSearch.columns = arrayCol;
//Populate the datagrid with the XML data.
dgSearch.dataProvider = xmlSrc.row;
}
Problem #1: The checkbox column appears, I can check and uncheck the checkboxes, but they are not checked/unchecked respective to DB data when loaded.
Problem #2: How do I associate a function to the checkboxes, for instance one which will update the XML so that I can save the new data to the DB?
Anybody got the solution? Thank you in advance.
Seems to be a very old question that I saw today.
Hopefully you would have found out the solution by now, just in-case if anyone has same problem:
While adding a checkbox to column- just instantiate it 1st:
var chkTempCheck: Checkbox = new CheckBox();
Then set all the properties required:
chkTempCheck.selected = o.dBColumnToDecideCheckUnCheck
here 'o' is the Object you are using from event.result.
This will work for sure!
The initial scenario was: all columns were defined in the mxml file. The checkbox column used itemrenderer and was working properly. I was using the same datagrid in 3 different cases - only thing was that some columns were set visible/invisible depending on the 'views'. The problem was when shifting 'views' and populate the grid and shift 'views' again, the column widths kept increasing exponentially. I excluded the checkbox column and everything worked fine; columns widths were ok. I included the checkbox column back and tried setting the column widths in AS file and the column-increasing-exponentially problem was fixed but the column widths were never the same when populating grid in view A and when populating grid in view B. ...So I ventured out in trying to set the columns in AS file just after obtaining DB data. Hope you can find yourself in those situations. Thanks for helping.

How to dynamically hide fields in a DetailsView (fields count is always 0)

I am using a DetailsView to show the details of a single row from a DataTable.
I do not know the column names at design time, so I have AutoGenerateRows = true in the markup.
DataView dv = myDataTable.AsDataView();
dv.RowFilter = string.Format("ResourceID = {0}", resourceId);
dvScoresBreakdown.DataSource = dv;
dvScoresBreakdown.DataBind();
There are about 4 columns in the DataView which I don't want the DetailsView to display - mainly ID columns.
I understand that I should access the Fields property of the DataView and set the relevant fields invisible:
dvScoresBreakdown.Fields[0].Visible = false;
dvScoresBreakdown.Fields[1].Visible = false;
However, the .Fields.Count is always zero. So I get an index out of bounds exception.
When I say "always zero", I mean it's zero right after the .DataBind(), and also in the OnDataBinding, OnDataBound, and OnPreRender events.
But, the DetailsView does render on the page and show everything - all the columns in the original DataView - so the dataview is binding!
What am I doing wrong?
I've just found out, the way to do it is to remove rows right after the .DataBind() method.
dvScoresBreakdown.DataSource = dv;
dvScoresBreakdown.DataBind();
dvScoresBreakdown.Rows[0].Visible = false;
dvScoresBreakdown.Rows[1].Visible = false;
Hope this can help someone else!
The Columns collection only stores the explicitly declared columns, so if you’re using autogenerated columns, the count will be zero.
If you’re using autogenerated column, after databind you could loop through the rows collection and make the appropriate cells invisible, like:
If dvScoresBreakdown is GridView
dvScoresBreakdown .DataBind();
if (dvScoresBreakdown .Columns.Count > 0)
dvScoresBreakdown .Columns[0].Visible = false;
else
{
dvScoresBreakdown .HeaderRow.Cells[0].Visible = false;
foreach (GridViewRow gvr in dvScoresBreakdown .Rows)
{
gvr.Cells[0].Visible = false;
}
}
I think this will help you.

binding a datagridview datasource to a datatable

i binded a datatable to a datagridview datasource. Now the problem is the columns in my datagridview cannot be customized. Does anyone know how to do this? It seems that the columns are dynamically created from the datasource. I need to custom to the font, color column names, etc... any thoughts?
If you are doing this in C# (?) you can set the datagridview AutoGenerateColumns property to false and dynamically add them yourself. This will then allow you to customise them.
The datagridview column has a DataPropertyName which you set to the name of the column in the datatable that you want it to display.
For example:
// Create new combo box column.
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
// Set properties.
column.DataPropertyName = colName;
column.Name = colName;
column.HeaderText = colName;
column.DropDownWidth = 160;
column.Width = 90;
column.MaxDropDownItems = 5;
column.FlatStyle = FlatStyle.Standard;
datagridview.Columns.Add(column);
You then just bind it to the datatable.
You should be able to auto-generate the columns and still customize them.
For example, to change a column's font you could do:
dataGridView.Columns["ColumnName"].DefaultCellStyle.Font = new Font("Tahoma, 15);
To change the colour of the column name:
dataGridView.Columns["ColumnName"].HeaderCell.Style.BackColor = Color.Blue;
I've tried both of these in an auto-generated DataGridView bound to a DataTable and it works for me.
Use annotation instead. Example :
internal class FailedItem
{
...
[DisplayName("Clarify reason")]
public string Reason
{ get; private set; }
...
}

How to write a filter condition when using a dataview

I have a datatable which contains all these records (see SQL query). Instead of writing a new stored procedure, how can I filter this condition in my datatable using dataview?
SELECT *
FROM students
WHERE class = '10'
AND Names IN ('kiran', 'manju', 'ram' , 'peter')
AND Language = 'english'
If you use the SQL in your question to create a new view, you could then run other queries against that view and have that filtering done automatically:
CREATE VIEW MYVIEW AS
SELECT * FROM students WHERE class='10'
AND Names IN ('kiran', 'manju', 'ram' , 'peter')
AND Language = 'english'
There is a nice article how to filter data using dataview there.
you would have to play with the RowFilter property of the Dataview.
private void MakeDataView()
{
DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.AllowDelete = true;
view.AllowEdit = true;
view.AllowNew = true;
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";
// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");
}
Note: You have to note since the filtering and sorting would be done on client side it might perform really poorly if you have too much rows.

Resources