I'm just trying to create a single button "view" click for the data in the specific row for gridview and pass it to a Silverlight viewer.
Here's a "viewall" button I'm trying to figure out off of.
protected void btnViewAll_Click(object sender, EventArgs e)
{
string id = HttpContext.Current.Request.Headers["id"];
#if DEBUG
if (id == null)
id = "111"; // Use my own id for testing locally
#endif
using (aDataContext dc = new aDataContext())
{
var query = (from a in dc.aLists
where a.ID == id
select new
{
a.aNumber,
a.bNumber,
a.cNumber,
a.dNumber,
}
);
List<aListItem> List = new List<aListItem>();
foreach (var queryItem in query)
{
aList.Add(new aListItem()
{
aNumber = queryItem.aNumber,
bNumber = queryItem.bNumber,
cNumber = queryItem.cNumber,
dNumber = queryItem.dNumber
});
}
Session["aList"] = aList;
}
Session["Database"] = null;
Response.Redirect("Viewer.aspx" + "?UseList=true");
}
Solution 1:
It can be done with a ButtonField in the GridView:
Add the row-specific info to the DataKeyNames of the GridView (e.g. if the fields "name1" and "age2" of your data source are needed to view with your Silverlight viewer):
<asp:GridView ID="gvClients" DataKeyNames="name1,age2" ... >
Add a ButtonField to the GridView:
<asp:ButtonField ButtonType="Button" CommandName="View" Text="View" />
Set the RowCommand event handler (can be done in markup or in code):
gvClients.RowCommand += new GridViewCommandEventHandler(gvClients_RowCommand);
And process the command:
void gvClients_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
string name1 = (string)gvClients.DataKeys[rowIndex].Values["name1"];
int age2 = (int)gvClients.DataKeys[rowIndex].Values["age2"];
// Open docName with the viewer
...
}
Solution 2: An alternative, which avoids a postback, would be to use a a HyperLinkField:
<asp:HyperLinkField Text="View" DataNavigateUrlFormatString="Viewer.aspx?Name={0}&Age={1}" DataNavigateUrlFields="name1,age2" />
Related
Using grid view binding it from code behind:
I want to bind a particular column data into a hyper link so when it clicked it should do a download.
How to do that ?
Below is my code :
for (int i = 0; i <= tbl.Columns.Count - 1; i++)
{
Telerik.Web.UI.GridBoundColumn boundfield = new Telerik.Web.UI.GridBoundColumn();
if (tbl.Columns[i].ColumnName.ToString() == "Row")
{
LinkButton lkbtn = new LinkButton();
lkbtn.CommandName = i;
lkbtn.CommandArgument = "dwnld";
lkbtn.Font.Underline = true;
lkbtn.Text = tbl.Columns(i).ColumnName.ToString();
boundfield.DataField = tbl.Columns(i).ColumnName.ToString()
boundfield.HeaderText = tbl.Columns(i).ColumnName.ToString();
GridView2.MasterTableView.Columns.Add(boundfield);
}
}
Why not use grid template column with link button.
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="btnDownload" OnClick="btnDownload_Click" runat="server">Download Something</asp:LinkButton>
</ItemTemplate>
</telerik:GridTemplateColumn>
protected void btnDownload_Click(object sender, EventArgs e)
{
LinkButton lbBtn = sender as LinkButton;
GridDataItem item = (GridDataItem)(sender as LinkButton).NamingContainer;
// Use item to get other details
...
...
}
From the title above, my code at the first time page_load, there is no problem, it show correctly but after I click button to change language, it is disappear(only show header). I spend about one week to find out but still cannot find what happen.
If the visible data MORE than 1, its working properly.
EDIT:
Forgot to put my page Load method
protected void Page_Load(object sender, EventArgs e)
{
NoResult.Visible = false;
Get_Data();
}
protected void Get_Data()
{
DBCAD.Service1 myCADDB = new DBCAD.Service1();
myCADDB.UseDefaultCredentials = true;
string result = "";
//set web service proxy
if (!GlobalVariable_CCCNS.filterOrNot)
{
//invoke web service method
result = myCADDB.CallCardStatus_Filter_CCCNSEMBILAN_ALL();
}
else
{
GlobalVariable_CCCNS.FilterDC = DropDownList1.SelectedValue;
//invoke web service method
if (GlobalVariable_CCCNS.FilterDC == "CCC NS ALL")
{
result = myCADDB.CallCardStatus_Filter_CCCNSEMBILAN_ALL();
}
else
{
result = myCADDB.CallCardStatus_Filter(GlobalVariable_CCCNS.FilterDC);
}
}
//read the response data and put in xml document
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(result);
string mypath = Server.MapPath(#"Data.xml");
//XmlTextReader reader = new XmlTextReader ("DBCAD.xml");
xmlDoc.Save(mypath);
//set the data set
DataSet ds = new DataSet();
ds.ReadXml(mypath);
//Open hidden column
CallCardStatus.Columns[0].Visible = true;
if (ds.Tables.Count > 0)
{
//list out the result to Data Grid
CallCardStatus.DataSource = ds;
CallCardStatus.DataBind();
}
else
{
NoResult.Visible = true;
}
//Clear Unwanted Column
CallCardStatus.Columns[0].Visible = false;
}
Here is my RowDataBound
string lastRow = "";
protected void CallCardStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Many item with same id but different status, I just want to visible and get the first row for each id.
if (e.Row.RowType == DataControlRowType.DataRow)
{
var thisRow = e.Row;
if (thisRow.Cells[0].Text == lastRow)
{
e.Row.Visible = false;
}
lastRow = thisRow.Cells[0].Text;
}
}
Here is my RadioButton for Language Malay and English
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
GlobalVariable_CCCNS.cultureName = RadioButtonList1.SelectedValue.ToString();
Page.Culture = GlobalVariable_CCCNS.cultureName;
Page.UICulture = GlobalVariable_CCCNS.cultureName;
if (GlobalVariable_CCCNS.cultureName == "ms-MY")
{
Label2.Visible = false;
Label2.Text = "Kawalan Status Kad Panggilan";
Label2.Visible = true;
}
else
{
Label2.Visible = false;
Label2.Text = "CallCard Status Monitoring";
Label2.Visible = true;
}
Page_Render();
}
protected void Page_Render()
{
Page.Culture = GlobalVariable_CCCNS.cultureName;
Page.UICulture = GlobalVariable_CCCNS.cultureName;
ALL.Text = GetLocalResourceObject("ALLResource1.Text").ToString();
Label1.Text = GetLocalResourceObject("Label1Resource1.Text").ToString();
NoResult.Text = GetLocalResourceObject("NoResultResource1.Text").ToString();
DBCAD.Service1 myCADDB = new DBCAD.Service1();
myCADDB.UseDefaultCredentials = true;
string result = "";
//set web service proxy
if (!GlobalVariable_CCCNS.filterOrNot)
{
//invoke web service method
result = myCADDB.CallCardStatus_Filter_CCCNSEMBILAN_ALL();
}
else
{
GlobalVariable_CCCNS.FilterDC = DropDownList1.SelectedValue;
//invoke web service method
if (GlobalVariable_CCCNS.FilterDC == "CCC NS ALL"){
result = myCADDB.CallCardStatus_Filter_CCCNSEMBILAN_ALL();
}else{
//invoke web service method
result = myCADDB.CallCardStatus_Filter(GlobalVariable_CCCNS.FilterDC);
}
}
//read the response data and put in xml document
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(result);
string mypath = Server.MapPath(#"Data.xml");
//XmlTextReader reader = new XmlTextReader ("DBCAD.xml");
xmlDoc.Save(mypath);
//set the data set
DataSet ds = new DataSet();
ds.ReadXml(mypath);
// CallCardStatus.DataSource = ds;
//CallCardStatus.DataBind();
//Open hidden column
CallCardStatus.Columns[0].Visible = true;
if (ds.Tables.Count > 0)
{
//list out the result to Data Grid
CallCardStatus.DataSource = ds;
CallCardStatus.Columns[2].HeaderText = GetLocalResourceObject("ButtonFieldResource1.Text").ToString();
CallCardStatus.Columns[3].HeaderText = GetLocalResourceObject("BoundFieldResource3.HeaderText").ToString();
CallCardStatus.Columns[4].HeaderText = GetLocalResourceObject("BoundFieldResource4.HeaderText").ToString();
CallCardStatus.Columns[5].HeaderText = GetLocalResourceObject("BoundFieldResource5.HeaderText").ToString();
CallCardStatus.Columns[6].HeaderText = GetLocalResourceObject("BoundFieldResource6.HeaderText").ToString();
CallCardStatus.Columns[7].HeaderText = GetLocalResourceObject("BoundFieldResource7.HeaderText").ToString();
CallCardStatus.Columns[8].HeaderText = GetLocalResourceObject("BoundFieldResource8.HeaderText").ToString();
CallCardStatus.Columns[9].HeaderText = GetLocalResourceObject("BoundFieldResource9.HeaderText").ToString();
CallCardStatus.DataBind();
}
else
{
NoResult.Visible = true;
}
//Clear Unwanted Column
CallCardStatus.Columns[0].Visible = false;
}
Anyone can help?Thanks..Siti..:)
In order to clean up your legacy code a little bit, I recommend you the following: (cleaning your code will help u to spot the error easier)
Binding your GridView
The best practice to bind a data-bound control is inside the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// in this method u will bind your GridView
this.BindGrid();
}
}
Unless I'm missing something, the code inside the Page_Render method is used to render your GridView, and that code is duplicated in the Get_Data method. You could place the code specific to bind your GridView inside one single method.
Now you only need to re-bind your GridView when its content has changed, for example if you allow your users to edit your GridView records. Otherwise, you should not re-bind it. (This is true, as long as your page has EnableViewState="true")
The code to localize your GridView columns can be moved to the GridVew.DataBound event. Or even better, delegate the logic to localize the view to your markup, to do it, you could create templated columns in your GridView.
Example:
<asp:GridView runat="server" DataSourceID="lds" ID="gv"
AutoGenerateColumns="false"
>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label Text="<%$ Resources: your_resource_file_name_without_extension, your resource_key %>" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="a_meaningfull_name" Text='<%# Eval("your_field_name") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Set the page language overriding the Page.InitializeCulture method:
Note that you only need to set this.UICulture = culture; and this.Culture = culture; inside this method
protected override void InitializeCulture()
{
// you have to call Request.Form, because at this point in the page life cycle, the page viewstate has not been loaded yet
var culture = this.Request.Form["RadioButtonList1"];
if (!string.IsNullOrWhiteSpace(culture))
{
// if the values of your list are culture specific (ie. en-US, es-MX, etc) you can uncomment the following line
// this.Culture = culture;
this.UICulture = culture;
base.InitializeCulture();
}
}
Using this approach you do not need the RadioButtonList1_SelectedIndexChanged event. The code you are placing inside this event won't be necessary.
This code:
if (GlobalVariable_CCCNS.cultureName == "ms-MY")
{
Label2.Visible = false;
Label2.Text = "Kawalan Status Kad Panggilan";
Label2.Visible = true;
}
else
{
Label2.Visible = false;
Label2.Text = "CallCard Status Monitoring";
Label2.Visible = true;
}
Can be easily eliminated using markup: (note that you will need to create one resource file for each language you want to use in your application, to learn more about ASP.Net Globalization click here)
Using global resources
<!-- Assuming global resources -->
<asp:Label runat="server" ID="Label2" Text="<%$ Resources: your_resource_file_name_without_extension, your_resource_key %>" />
Your global resource file would look like:
<data name="your_resource_key" xml:space="preserve">
<value>your text</value>
</data>
Using local resources
<!-- Assuming local implicit resources -->
<asp:Label runat="server" ID="Label2" meta:resourcekey="base_name_of_your_resource_key" Text="default value used to render the control at design time in VS" />
In this case, your local resource file would look like:
<data name="base_name_of_your_resource_key.Text" xml:space="preserve">
<value>your text</value>
</data>
You do not need to call Page_Render(); in the RadioButtonList1_SelectedIndexChanged event
I want to bind my grid column header names by retrieving data from a table. This table has two fields, DomainID and DomainName, I want to display the DomainNames as Column header of the Grid.
Actually I am creating employee grid view. I want all the domain names of employee to be displayed as a header and i have to check the corresponding domain in Checkbox.
Please Give me some ideas.
Thanks in advance.
From what i understood....
Make a grid view
Create two columns:
a. TextBoxColumn
b. CheckBoxColumn
Set your column header using .HeaderText property
Add the columns to your data grid view
Query your database and get the data_table from it
using dgv.DataSource = data_table bind your data to the table
OR
Make a for loop for all rows in the data_table and add each row explicitly
For getting your checkboxes to work, handle the cellContentClick event of the data grid view and perform the necessary updates in your database.....
Hope it helps....
You could load the headers into a DataTable and then create them dynamically with a custom TemplateField.
Here's the aspx part:
<asp:GridView ID="GridView1" AutoGenerateColumns="false" DataKeyNames="EmployeeID" runat="server" >
<SelectedRowStyle BackColor="Aqua" />
<Columns>
<asp:TemplateField HeaderText="Employee" SortExpression="Employee">
<ItemTemplate>
<asp:HiddenField ID="HiddenEmpID" Value='<%# Bind("EmployeeID") %>' runat="server" />
<asp:label runat="server" ID="LblEmployee" Text='<%# Bind("EmployeeName") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="BtnSave" Text="Save" runat="server" onclick="BtnSave_Click" />
Here's a complete sample:
public partial class GridTest : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
CreateGridColumns();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) BindGrid();
}
private void CreateGridColumns()
{
var tblDomain = GetDomains();
// Create dynamic TemplateFields
foreach (DataRow row in tblDomain.Rows)
{
String domainName = row.Field<String>("DomainName");
TemplateField field = new TemplateField();
//Initalize the DataField value.
field.ItemTemplate = new GridViewCheckBoxTemplate(ListItemType.Item, domaninName);
field.HeaderText = domainName;
//Add the newly created field to the GridView.
GridView1.Columns.Add(field);
}
}
private DataTable GetDomains()
{
var tblDomain = new DataTable();
tblDomain.Columns.Add("DomainID", typeof(int));
tblDomain.Columns.Add("DomainName");
tblDomain.Rows.Add(1, "Google.com");
tblDomain.Rows.Add(2, "Yahoo.com");
tblDomain.Rows.Add(3, "Msn.com");
tblDomain.Rows.Add(4, "Youtube.com");
tblDomain.Rows.Add(5, "Myspace.com");
tblDomain.Rows.Add(6, "Facebook.com");
tblDomain.Rows.Add(7, "Wikipedia.org");
return tblDomain;
}
private void BindGrid()
{
var tblDomain = GetDomains(); // load domains from database or wherever
var tblData = new DataTable();// load sample data
tblData.Columns.Add("EmployeeID", typeof(int));
tblData.Columns.Add("EmployeeName");
//add domains as DataTable-Columns
foreach (DataRow row in tblDomain.Rows)
{
String domaninName = row.Field<String>("DomainName");
//Add column from domain-name
tblData.Columns.Add(domaninName, typeof(bool)); //CheckBox-Checked is a boolean
}
//get some Employees and random checked state
var rnd = new Random();
var empRow = tblData.NewRow();
empRow["EmployeeID"] = 1;
empRow["EmployeeName"] = "Jon";
foreach (DataRow dom in tblDomain.Rows)
{
empRow[dom.Field<String>("DomainName")] = rnd.Next(0, 2) == 0;
}
tblData.Rows.Add(empRow);
empRow = tblData.NewRow();
empRow["EmployeeID"] = 2;
empRow["EmployeeName"] = "Eric";
foreach (DataRow dom in tblDomain.Rows)
{
empRow[dom.Field<String>("DomainName")] = rnd.Next(0, 2) == 0;
}
tblData.Rows.Add(empRow);
empRow = tblData.NewRow();
empRow["EmployeeID"] = 3;
empRow["EmployeeName"] = "Alain";
foreach (DataRow dom in tblDomain.Rows)
{
empRow[dom.Field<String>("DomainName")] = rnd.Next(0, 2) == 0;
}
tblData.Rows.Add(empRow);
GridView1.DataSource = tblData;
GridView1.DataBind();
}
// show how to retrieve all checkbox values and the according EmployeeID
protected void BtnSave_Click(object sender, EventArgs e)
{
if (GridView1.Rows.Count == 0) return;
var checkBoxColumns = GridView1.Columns.Cast<DataControlField>()
.Select((bf,index) => new{Field=bf, Index=index})
.Where(f => f.Field.GetType() == typeof(TemplateField) && ((TemplateField)f.Field).ItemTemplate.GetType() == typeof(GridViewCheckBoxTemplate))
.ToArray();
foreach (GridViewRow row in GridView1.Rows)
{
int EmployeeID = int.Parse(((HiddenField)row.FindControl("HiddenEmpID")).Value);
foreach (var f in checkBoxColumns)
{
String domain = f.Field.HeaderText;
bool isChecked = row.Controls[f.Index].Controls.OfType<CheckBox>().First().Checked;
}
}
}
}
Here's the custom ITemplate:
public class GridViewCheckBoxTemplate : ITemplate
{
ListItemType _templateType;
string _columnName;
public GridViewCheckBoxTemplate(ListItemType type, string colname)
{
_templateType = type;
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
break;
case ListItemType.Item:
var chb1 = new CheckBox();
chb1.DataBinding += new EventHandler(CB_DataBinding);
container.Controls.Add(chb1);
break;
case ListItemType.EditItem:
//As, I am not using any EditItem, I didnot added any code here.
break;
case ListItemType.Footer:
break;
}
}
void CB_DataBinding(object sender, EventArgs e)
{
CheckBox chb = (CheckBox)sender;
GridViewRow container = (GridViewRow)chb.NamingContainer;
object dataValue = ((DataRowView)container.DataItem)[_columnName];
chb.Checked = dataValue != DBNull.Value && (bool)dataValue;
}
}
I have a FormView that I user for updating a record. There is a link button that when fires should perforom the updating via BLL and DAL. I am not using built-in ODS and I will not condsider using it.
I have all my grids and formviews populated manuualy by calling methods that fetch the data from the database.
For instance my details view is populated like this:
protected void DlMembers_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.ToString() == "Select")
{
DlMembers.Visible = false;
lblError.Text = string.Empty;
lblError.Visible = false;
fvMemberDetail.Visible = true;
fvMemberDetail.ChangeMode(FormViewMode.Edit);
MemberBLL getMemberInfo = new MemberBLL();
int Ident = Convert.ToInt32(e.CommandArgument.ToString());
fvMemberDetail.DataSource = getMemberInfo.GetMemberByIdent(Ident);
fvMemberDetail.DataBind();
}
if (e.CommandName.ToString() == "DeleteSelected")
{
DlMembers.Visible = true;
lblError.Text = string.Empty;
lblError.Visible = false;
fvMemberDetail.Visible = false;
fvMemberDetail.ChangeMode(FormViewMode.ReadOnly);
}
What I want to do if to capature my linkbutton on click event and do this (except that the runtime never reaches this method):
protected void MemberInfoUpdating(object sender, EventArgs e)
{
TextBox id = (TextBox)fvMemberDetail.FindControl("txtIdent");
if (id.Text != string.Empty || id.Text != "")
{
TextBox txtFN = (TextBox)fvMemberDetail.FindControl("txtFN");
TextBox txtLN = (TextBox)fvMemberDetail.FindControl("txtLN");
DropDownList ddlAddress = (DropDownList)fvMemberDetail.FindControl("ddlAddress");
TextBox txtEmail = (TextBox)fvMemberDetail.FindControl("txtEmail");
TextBox txtHPhone = (TextBox)fvMemberDetail.FindControl("txtHPhone");
TextBox txtWPhone = (TextBox)fvMemberDetail.FindControl("txtWPhone");
TextBox txtMPhone = (TextBox)fvMemberDetail.FindControl("txtMPhone");
DropDownList ddlPos = (DropDownList)fvMemberDetail.FindControl("ddlPos");
DropDownList ddlIsAdmin = (DropDownList)fvMemberDetail.FindControl("ddlIsAdmin");
bool blIsAdmin = false;
if (ddlIsAdmin.SelectedValue == "True") blIsAdmin = true;
TextBox txtComments = (TextBox)fvMemberDetail.FindControl("txtComments");
MemberBLL updateMemberInfo = new MemberBLL();
bool UpdateOK = updateMemberInfo.UpdateMemberByIdent(
txtFN.Text,
txtLN.Text,
ddlAddress.SelectedValue,
txtEmail.Text,
txtHPhone.Text,
txtWPhone.Text,
txtMPhone.Text,
blIsAdmin,
txtComments.Text,
Convert.ToInt32(ddlPos.SelectedValue),
Convert.ToInt32(id.Text));
}
else
{
//Display error - no user id cannot update record
}
}
The linkbutton looks like this:
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
OnClick="MemberInfoUpdating" Text="Update" />
Where is this LinkButton? If it's inside a FormView template, then you'll likely need to use something like this instead:
<asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
Then handle the "Update" command in DlMembers_ItemCommand.
Alternatively, attach your code to the OnItemUpdating event of the FormView rather than some extra event you don't need:
<asp:FormView ID="fvMemberDetail" runat="server" OnItemUpdating="MemberInfoUpdating">
I group my data by length as follows
int[] a = { 1, 2, 3,45,45,100,566};
var result =
a.GroupBy(x => x.ToString().Length).
Select(d => new { Key = d.Key, Grp = d });
My BulletedList is nested in GridView(placed as template field) to display the items,What is the way to bind the BulletedList when GridView displays "Key".
GridView1.DataSource = result;
GridView1.DataBind();
set DataKeyNames to your key name
For example:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSource"
autogeneratecolumns="true"
emptydatatext="No data available."
autogenerateselectbutton="true"
datakeynames="CustomerID"
Binding to a bulleted list within a gridview (works similarly for any control, of course)
void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
RadioButtonList list = (RadioButtonList)e.Row.FindControl("rbList");
if(list != null)
{
list.DataSource = mysource;
list.DataBind();
}
}
}
Make sure you add the event to the GridView.