Dynamically adding Devexpress GridControl to C# windows application - devexpress

I want to add Devexpress GridControl dynamically. At runtime I want to show the Filter Row. Also I want to have a button on the same form that has the dynamically created GridControl. When the button is clicked it should show the Filter Dialog popup for the grid control.

The provided sample does what you ask for.
Create a Form called Form1.
Create a Button called button1 and Dock it to
the top of the form.
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
namespace Samples
{
public partial class Form1 : Form
{
private GridControl grid;
private GridView view;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
view.ShowFilterPopup(view.Columns[0]);
}
private void Form1_Load(object sender, EventArgs e)
{
grid = new GridControl();
view = new GridView();
grid.Dock = DockStyle.Fill;
grid.ViewCollection.Add(view);
grid.MainView = view;
view.GridControl = grid;
view.OptionsView.ShowAutoFilterRow = true;
GridColumn column = view.Columns.Add();
column.Caption = "Name";
column.FieldName = "Name";
column.Visible = true;
// The grid control requires at least one row
// otherwise the FilterPopup dialog will not show
DataTable table = new DataTable();
table.Columns.Add("Name");
table.Rows.Add("Hello");
table.Rows.Add("World");
grid.DataSource = table;
this.Controls.Add(grid);
grid.BringToFront();
}
}
}

Related

Search in a xml gridview.

This is my first question here at Stack Overflow and i will be as precise as possible.
I am working on an ASP.NET Web application and i have a gridview which have a XML as a datasource. I already have it bound as a datasource and it works perfect.
I have a textbox and a button in my project and want to search in the gridview.
Here is an example of one of the nodes in the XML file.
https://i.imgur.com/weTlrh1.png
The problem I currently have is that I am stuck at the search gridview part.
I have as I said before a textbox and a button and when i write a value in the textbox and press on the button i want to search the gridview and its nodes to check if for an example any titles contains the words from the textbox.
Right now I have the corresponding code:
https://i.imgur.com/l2lz8JL.png
This code is in the buttonSearch Click event. The SearchBookBox.text is the Text i want to search for in the Gridview.
I am stuck right now and i need some help.
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("/NewFolder1/books.xml"));
GridView1.DataSource = ds;
GridView1.DataBind();
The above code is the code which i bind the gridview to the corresponding xml file. This code is in my Page_Load Event.
I have tried different ideas to solve this issue, but nothing works.
Right now the code is like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace BookSearch
{
public partial class BookSearchForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ErrorLabel.Visible = false;
AddBooksXML();
}
private void AddBooksXML()
{
if (!IsPostBack)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("/NewFolder1/books.xml"));
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void BookSearchButton_Click(object sender, EventArgs e)
{
if(SearchBookBox.Text != null)
{
foreach (XmlNode node in ds.GetXml)
{
}
}
else
{
Response.Write("ERROR!");
}
}
}
}
I really need some help. As i said, i have tried different ideas, but I am stuck and I can't get anywhere.
I think this is a possible solution.
protected void XmlSearch(string searchText)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("/NewFolder1/books.xml"));
var dat = from books in ds.Tables[0].AsEnumerable()
where books.Field<string>("author") == searchText || book.Field<string>("title") == searchText
select books;
GridView1.DataSource = dat.CopyToDataTable();
GridView1.DataBind();
}
This will search in author and title for exact matches its probably not the best solution but its a example of how you could do it.
Requires
using System.Linq;
EDIT
If you wanna loop through them you can use
foreach (var book in dat)
{
var bookInfo = String.Format("{0} {1}", book["author"].ToString(), book["title"].ToString());
}

telerik asp radgrid subclassed column adding and getting custom properties

Here are is my column class and i've added this code to my radgrid
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Telerik.Web.UI;
namespace EFDemo.Views.Controls
{
public class HpGridButtonColumn : GridButtonColumn{
public string LinkedTab;
public override void InitializeCell(System.Web.UI.WebControls.TableCell cell, int columnIndex, Telerik.Web.UI.GridItem inItem)
{
//if (inItem is GridHeaderItem)
//{
// cell.Text = this.DataField;
//}
//if (inItem is GridDataItem)
//{
// string ID = (string) inItem.OwnerTableView.DataKeyValues[inItem.ItemIndex]["CustomerID"];
// cell.Controls.Add(new LiteralControl(ID));
//}
base.InitializeCell(cell, columnIndex, inItem);
}
public override GridColumn Clone()
{
HpGridButtonColumn col = new HpGridButtonColumn();
//you should override CopyBaseProperties if you have some column specific properties
col.CopyBaseProperties(this);
return col;
}
protected override void CopyBaseProperties(GridColumn FromColumn)
{
base.CopyBaseProperties(FromColumn);
((HpGridButtonColumn)FromColumn).LinkedTab = LinkedTab;
}
}
}
protected void HPRadgrid_ColumnCreating(object sender, GridColumnCreatingEventArgs e)
{
if ((e.ColumnType == typeof(HpGridButtonColumn).Name))
{
e.Column = new HpGridButtonColumn();
}
}
Problem is the property [linkedTab] is not being restored on postback. It is null.
Also, the clone method on the column is not being called. I assume this is why the property is not being restored.

Clarification on Caching in ASP.NET

We were working on data caching in ASP.Net where we have aspx page which has a Label and a Button.
Label will show Cached data if Cache is not null else it will load the data into cache and display "DataReloading" in the Label and a Click of a Button should clear the data from the cache and Label should show "DataReloading" and when we refresh the page again, label should show Cache Data
Expectation:
1) when First time page loads, Label should show "DataReloading" as Cache was empty and we are loading the data
2) when we Refresh , Label should show "Cache Data" as Cache was having "Cache Data" string in it
3) When we click button to Clear cache, Label should show "DataReloading" and when we refresh the page label should show Cache Data
The Problem that we are facing is on post button click we always get "DataReloading" in the Label.
Can anyone let us know where logic is wrong.
Here is a code from the aspx page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FormAuthenticationPractice
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCache();
}
private string GetData()
{
return "Cache Data";
}
protected void btnClearCache_Click(object sender, EventArgs e)
{
Cache.Remove("Data");
lblData.Text = "DataReloading";
}
private void LoadCache()
{
if (Cache["Data"] != null)
{
lblData.Text = Convert.ToString(Cache["Data"]);
}
else
{
Cache["Data"] = GetData() as string;
lblData.Text = "DataReloading";
}
}
}
}

Server Control with dropdown and button, and trigger own event

i have a C# server control which contains one button and one dropdown
i want to response.write the dropdown selectedindex to the page while the button click
and i dont want to make the event handler on page level (aspx), but i want to code it inside the control and compile as dll
my flow is :
construct the button and dropdown, which the control class is load
override CreateChildControls to add the button into the server control and bind the click event to it
override the RenderControl to add the dropdown to a table, and then render the button
finally i found that the button event can be click, but it just cant get the dropdown selected item, when i select the second one
here is the code :
public class ServerControl1 : WebControl, INamingContainer
{
public ServerControl1()
{
_oBtn = new Button();
_oBtn.ID = "btn";
_oBtn.Text = "Click Me";
_oBtn.Click += new EventHandler(_oBtn_Click);
_ddl = new DropDownList();
_ddl.ID = "ddl";
_ddl.Items.add(new ListItem("xxxxxxxx", "xxxxxxxx"))
_ddl.Items.add(new ListItem("yyyyyyy", "yyyyyyy"))
}
protected override void CreateChildControls()
{
this.Controls.Add(_oBtn);
base.CreateChildControls();
}
public override void RenderControl(HtmlTextWriter writer)
{
AddAttributesToRender(writer);
Table m_oTable = new Table();
TableRow m_oRow;
TableCell m_oCell;
m_oCell = new TableCell();
m_oCell.Controls.Add(_ddl);
m_oRow.Cells.Add(m_oCell);
m_oTable.Rows.Add(m_oRow);
m_oTable.RenderControl(writer);
_oBtn.RenderControl(writer);
}
protected void _oBtn_Click(object sender, EventArgs e)
{
if (_ddl.SelectedIndex != 0)
{
Page.Response.Redirect(Url + "&f0=" + _ddl.SelectedIndex);
}
else
{
Page.Response.Write("nonononon");
}
}
}
In order to preserve the state (ViewState) of the dynamically added controls (button, dropdownlist), you have to make sure they are added to the Control Tree hierarchy.
-> Page
-> WebControl
-> Button
-> DropdownList
The proper way to initialize the Child controls in a WebControl is in the Init event.
/// <summary>
/// Initialization of controls
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
_oBtn = new Button();
_ddl = new DropDownList();
m_oTable = new Table();
m_oRow = new TableRow();
m_oCell = new TableCell();
_oBtn.ID = "btn";
_oBtn.Text = "Click Me";
_oBtn.Click += new EventHandler(_oBtn_Click);
_ddl.ID = "ddl";
_ddl.Items.Add(new ListItem("xxxxxxxx", "xxxxxxxx"));
_ddl.Items.Add(new ListItem("yyyyyyy", "yyyyyyy"));
_ddl.EnableViewState = true;
_ddl.AutoPostBack = false;
}
If IsPostaback than before the Load event of the control, the state of the Child controls is restored from the ViewState (ex: current button text and selected index are set).
Next step is to add this child controls in the Control Tree hierarchy in the CreateChildControls method
protected override void CreateChildControls()
{
m_oCell.Controls.Add(_ddl);
m_oRow.Cells.Add(m_oCell);
m_oTable.Rows.Add(m_oRow);
this.Controls.Add(_oBtn);
this.Controls.Add(m_oTable);
base.CreateChildControls();
}
and to render the control. You have to avoid initializing or adding controls at this point on:
public override void RenderControl(HtmlTextWriter writer)
{
m_oTable.RenderControl(writer);
_oBtn.RenderControl(writer);
_txt.RenderControl(writer);
}

Any Way To get The selected Indices only in CheckBoxList?

I want to get the selected Indices or Items only in checkBox lsit instead of iterating through each item as Like is there in ListBox.
I am Getting Selected Value In tWo case In this way:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class ChkBxList_2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string li = "";
foreach(ListItem lt in CheckBoxList1.Items)
{
if(lt.Selected)
li += lt.Text;
}
Response.Write(li);
}
protected void Button2_Click(object sender, EventArgs e)
{
string li = "";
foreach (int lt in ListBox1.GetSelectedIndices())
{
li += ListBox1.Items[lt].Text;
}
Response.Write(li);
}
}
In ListBox we have the Option To get Seected Only Items is there any For Check Box List?
I dont think there is but you could use this extension method that does exactly that:
public List<ListItem> GetSelectedItems(this CheckBoxList checkBoxList)
{
List<ListItem> list = new List<ListItem>();
foreach(ListItem lt in checkBoxList)
{
if(lt.Selected)
list.Add(lt);
}
return list;
}
//Call it like this
checkBoxList.GetSelectedItems();
You actually answered your own question. There is no way to get the selected only items in the CheckBoxList control, unlike the ListBox control.
This article has an explanation and a work around help method.
http://weblogs.asp.net/jgalloway/archive/2005/10/02/426346.aspx

Resources