How to add values to DataGridColumn dynamically in ASP.net - asp.net

In the project I am working in there is webpage which retrieve data from the database. So I have used DataGrid show my data.
But sometimes I wanted to add more columns to the DataGrid.That means I want to add some columns with data dynamically.
However I have new columns addition to the DataGrid and here is my code.
DataGridColumn myCol = new BoundColumn();
myCol.HeaderText = "Test";
myCol.Visible = true;
grdHeiskort.Columns.Add(myCol);
In here "grdHeiskort" is DataGrid ID.Now I want to add the data to this column named="test".That data is gain from the database.Suppose I am retrieving dataset from DB and I want to add the data in 1st column in dataset to my "test" column.So how can I do it.

If you use a BoundColumn you can set the name of the DataField to whatever the name of the field you want it to be from your dataset:
BoundColumn myCol = new BoundColumn();
myCol.HeaderText = "Test";
myCol.Visible = true;
myCol.DataField = "NameOfYourDataColumn";
grdHeiskort.Columns.Add(myCol);

Related

getting value of column in spreadsheet

I am using devexpress and when I try to get value of a spreadsheet's cell using below code:
Workbook workbook = new Workbook();
Column firstColumn_byName = columns["A"];
I get the following error:
the name columns does not exist in the current context
You haven't defined columns.
Workbook workbook = new Workbook();
// Access a collection of columns.
ColumnCollection columns = workbook.Worksheets[0].Columns;
// Access the first column by its unique name.
Column firstColumn_byName = columns["A"];
Taken from: devexpress documentation

Inserting Gridview Column from code behind based on random index in asp.net

I am trying to insert column into gridview, I have dropdown below the grid and dropdown is having 10 items now If i select random item assume that I am selecting 8 number item and add clicking add button. this item should create as new column at 8 number in grid.
Suppose grid is not having any column when page is loading and trying to insert column using below code throwing error.
var boundField = new TemplateField { HeaderText = "SelectedProductName"};
grd.Columns.Insert(ddlProduct.SelectedIndex, boundField);
As Selected index can be any random number but grd is throwing out of index error as grid does not have that position.
Could you please help me to insert new column based on selected index from the dropdown.
My goal to achieve to display grid columns as they are listing into the dropdown same sequence.
First I defined a new class that will help us to store the columname and the index of that column in the dropdownlist:
public MyColumnClass
{
public MyColumnClass();
public int DDLindex {get;set;}
public string ColumnName{get;set;}
}
Here is the main code, each time a new column added, the following code will re-order them, based on their order in the dropdownlist:
BoundField boundField = new BoundField();
boundField.DataField = drp_Items.SelectedItem.Text;
boundField.Headertext = "Item";
myGridView.Columns.Insert(0, boundField);
//this list will store the existing
List<MyColumnClass> columnList = new List<MyColumnClass>();
for(int x = 0; x < myGridView.Columns.Count; x++)
{
//dropdownlist index of the column
var a = drp_Items.Items.IndexOf(drp_Items.Items.FindByValue(myGridView.Columns[x].DataField));
MyColumnClass column = new MyColumnClass();
column.DDLindex = a;
column.ColumnName= myGridView.Columns[x].DataField;
columnList.Add(column);
}
/the column list is created above, now we can clear the existing columns, and regenerate with the correct order
myGridView.Columns.Clear();
foreach(MyColumnClass item in columnList.OrderBy(c => c.DDLindex))//we order the list based on DDLindex
{
BoundField boundField = new BoundField();
boundField.DataField = item.ColumnName;
boundField.Headertext = "Item";
myGridView.Columns.Add(boundField);
}
P.S. You should make autogeneratecolumns="false" if you are binding data to Gridview.

Format XML data to display on a gridview

I am trying to format XML data to display on a grid.
Page1.aspx. This inserts XML data stored a xmldatatype:
WorkHistory workhis = js.Deserialize<WorkHistory>(json);
XmlDocument work = (XmlDocument)JsonConvert.DeserializeXmlNode(json, "root");
objBLL.insert_XMLWork(work, Convert.ToInt64(ui.id));
Page2.aspx retrieves it and display on a grid:
DataTable FBWorkDt = objBLL.get_FacebookWork(FacebookUserId);
GrdWork.DataSource = FBWorkDt;
GrdWorkPub.DataBind();
get_FacebookWork(select workinfo from Fprofiles where Userid = FacebookUserId)
returns a DataTable
It displays in this format exactly.
WorkInfo
<root><work><employer><id>208571635850052</id><name>Netizen Apps</name></employer></work><id>1076483621</id></root>
How do I make a normal display instead of XML format?
Thanks
Sun
It depends a good deal on the shape of the DataTable you're returning, but assuming you want the display to be something like this:
`ID Name
-------------------- ---------------------
208571635850052 Netizen Apps`
You could use LINQ:
DataTable FBWorkDt = objBLL.get_FacebookWork(FacebookUserId);
var query = from x in FBWorkDt.AsEnumerable()
select new {
id = x.ID,
name = x.Name
};
GrdWork.DataSource = query.ToList();
GrdWorkPub.DataBind();
I haven't tried the code out, so there may be minor syntatic changes, but essentially what it's doing is:
Use LINQ to get a collection of a new anonymous type that has one entry per row with the id and name from the table. You have to use AsEnumerable() [contained in System.Data.DataSetExtensions].
Convert the LINQ result set to a List via .ToList() and bind it to the GridView.
If you can post a little more information - what exactly you mean by display, and the expected shape of the returned DataTable (i.e., what the columns in each row are) we can give you a better answer.
UPDATE
If you're storing the XML document above in your datastore and that is being returned in the table, try this code:
DataTable FBWorkDt = objBLL.get_FacebookWork(FacebookUserId);
XDocument xDoc = XDocument.Load(FBWorkDt.Rows[0][0].ToString());
var query = from x in xDoc.Descendants("employer")
select new
{
id = (string)x.Element("id"),
name = (string)x.Element("name")
}
GrdWork.DataSource = query.ToList();
GrdWorkPub.DataBind();
Same basic principal as above, except this time your querying over an XDocument instead of a DataTable.

Edit the code of a GridView column asp.net

I've been looking for a way to control the text that appears in a particular column of a GridView.
For example consider a database with two tables Student and Class.
I want to add a column to the GridView which print out all the students in the Database, the column will show the student's class name, how can do it? (I can normally print the ClassId since its a FK in the student table)
I want to add a column to the GridView which print all the classes, the column will count the number of students in each class, how can I do it?
1- You can do that simply with inner join or a stored procedure to get the class name beside all the data you need in your query.
2- More than one way to do what you want:
For example:
you can add a column to your data table (empty column ), and fill it later through using Sum() aggregate function in a query.
DataTable result_dt = DAL_Helper.Return_DataTable(sqlSelect);//your original query
result_dt.Columns.Add("NumberOfStudent");
result_dt.Columns["NumberOfStudent"].DataType = typeof(string);
result_dt.Columns["NumberOfStudent"].MaxLength = 255;
if (result_dt.Rows.Count > 0)
{
for (int i = 0; i < result_dt.Rows.Count; i++)
{
//Here u can fill your new empty column.
}
}
result_dt.AcceptChanges();
After you return your customized data table(as a data source), you can bind it to the grid view.
Another solution : add an empty column to the grid view and in the RowDataBound event of the grid view you can fill this column through some loop and you can use LINQ to help you in getting the summation.

How to set dropdown's firsl Item -Select- and remaining Items from a column of table?

I m using a dropdown to display "Location" field of a table. I want to set first item of dropdowm as "-Select Location-". I can't set tables first record as "Select" because table is stroed in xml format. And table file is generated dynamicaly.
I am currentaly using as
ddlLocationName.Dispose();
ddlLocationName.AppendDataBoundItems = true;
ddlLocationName.Items.Add("Select Location");
ddlLocationName.DataSource = _section.GetLocations();
ddlLocationName.DataBind();
ddlLocationName.AppendDataBoundItems = false;
but data is binded repeatedly.
What will be the solution for this problem?
Thaks in advance.
After you have databound, then call ddlLocationName.Items.Insert(0, "Select Location");
Example:
ddlLocationName.Items.Clear();
ddlLocationName.DataSource = _section.GetLocations();
ddlLocationName.DataBind();
ddlLocationName.Items.Insert(0, "Select Location"); // Adds the item in the first position
Access the items in the form of ListItems:
ListItem li = new ListItem("Select Location","-1");
ddlLocationName.Items.Add(li);
After you have bound your other data, use:
ddlLocationName.SelectedValue = "-1";
Also, you can add the values of your table in similar way to the ListItem first.

Resources