I have some radiobuttons on some tabs, when I click on one it generates an Excel-file.
<asp:RadioButton ID="rbAantallen1" runat="server" AutoPostBack="True"
GroupName="Soort" oncheckedchanged="rbRapport_CheckedChanged"
Text="Aantallen" />
The bug happens when I want to switch to the other tab. It keeps generating Excel-files. What can I do to stop running the checkedchanged event and SWITCH IN PEACE TO ANOTHER TAB?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MyDataSource.SelectCommand = #"
select melder_account,
aanvraag_titel,
fase_datum_opgelost_oplosser,
Melding_niveau_2,
rapporteren,
fase_datum_gestart,
fase_datum_opgelost,
doorlooptijd,
jurentkode
from uvw_HD_AANVRAAG_DOORLOOPTIJD_ALGEMEEN
where Melding_niveau_1 = 'Brandje'";
}
}
protected void MenuTabs_MenuItemClick(object sender, MenuEventArgs e)
{
int index = Int32.Parse(e.Item.Value);
multiTabs.ActiveViewIndex = index;
MyDataSource.SelectCommand = BepaalDataSource(index);
}
public string BepaalDataSource(int index)
{
string select = #"
select melder_account,
aanvraag_titel,
fase_datum_opgelost_oplosser,
Melding_niveau_2,
rapporteren,
fase_datum_gestart,
fase_datum_opgelost,
doorlooptijd,
jurentkode
from uvw_HD_AANVRAAG_DOORLOOPTIJD_ALGEMEEN
where Melding_niveau_1 = '";
if (index == 0)
{
cbPage.Checked = false;
return select += "Brandje'";
}
else
{
cbPage.Checked = true;
return select += "System - Netwerk'";
}
}
public DataView GetDataFromDataSource()
{
MyDataSource.SelectCommand = BepaalDataSource(Convert.ToInt16(cbPage.Checked));
return MyDataSource.Select(DataSourceSelectArguments.Empty) as DataView;
}
protected void rbRapport_CheckedChanged(object sender, EventArgs e)
{
DataTable dtOriginal = (DataTable)GetDataFromDataSource().ToTable(); //Return Table consisting data
DataTable dtTemp = new DataTable(); //Create Temporary Table
//Creating Header Row
dtTemp.Columns.Add("<b>Melder</b>");
dtTemp.Columns.Add("<b>Onderwerp</b>");
dtTemp.Columns.Add("<b>Oplosser</b>");
dtTemp.Columns.Add("<b>Niveau 2</b>");
dtTemp.Columns.Add("<b>Rapporteren</b>");
dtTemp.Columns.Add("<b>Gestart op</b>");
dtTemp.Columns.Add("<b>Opgelost op</b>");
dtTemp.Columns.Add("<b>Doorlooptijd</b>");
dtTemp.Columns.Add("<b>Jurentkode</b>");
DataRow drAddItem;
for (int i = 0; i < dtOriginal.Rows.Count; i++)
{
drAddItem = dtTemp.NewRow();
drAddItem[0] = dtOriginal.Rows[i][0].ToString();//Melder
drAddItem[1] = dtOriginal.Rows[i][1].ToString();//Onderwerp
drAddItem[2] = dtOriginal.Rows[i][2].ToString();//Oplosser
drAddItem[3] = dtOriginal.Rows[i][3].ToString();//Niveau 2
drAddItem[4] = dtOriginal.Rows[i][4].ToString();//Rapporteren
drAddItem[5] = dtOriginal.Rows[i][5].ToString();//Gestart op
drAddItem[6] = dtOriginal.Rows[i][6].ToString();//Opgelost op
drAddItem[7] = dtOriginal.Rows[i][7].ToString();//Doorlooptijd
drAddItem[8] = dtOriginal.Rows[i][8].ToString();//Jurentkode
dtTemp.Rows.Add(drAddItem);
}
DataGrid dg = new DataGrid(); //Temp Grid
dg.DataSource = dtTemp;
dg.DataBind();
ExportToExcel("Rapport.xls", dg);
dg = null;
dg.Dispose();
}
private void ExportToExcel(string strFileName, DataGrid dg)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
protected void cbRapport_CheckedChanged(object sender, EventArgs e)
{
}
A couple things come to mind.
In your rbRapport_CheckChanged() function you could check to make sure the radio button is visible.
You could also check your tab control to make sure you're on the right tab.
EDIT
Based on your comments, the hosting tab is invisible.
If that's the case, do something like this in your code
rbRapport_CheckChanged()
{
if(tab1.Visible == false)
return;
<rest of code here>
}
Where tab1 is the tab that rbRapport is on. This will check, if the tab isn't visible, you probably don't want to create an xls, so it will just short circuit and kick out of the event. If the tab is visible, it will process the event.
Edit
maybe you shouldn't be creating the xls when your radio button changes. Maybe you should have a button to click that says "Generate XLS" or something, and capture that click event. – taylonr Apr 28 at 11:42
Nothing wrong with the code provided. Please ensure that, you have not bind this rbRapport_CheckedChanged function with any other control's event like TabChangedEvent or CheckedChange event of other radio button which values will be changing based on tab change etc.
If not so, there may be problem with the parent controls of the RadioButton.
Related
I have a checkbox that I am adding to a server control. This checkbox is not getting the usual onclick...__doPostBack() call added to it either. This results in it not causing a postback like I would like it to.
private void CreateGrid()
{
StringWriter sWriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(sWriter);
GridItem.ID = "gridItem";
GridHeader.ID = "gridHeader";
GridHeader.Attributes["class"] += " no-select";
GridCount.ID = "GridCount";
GridDescription.ID = "GridDescription";
if (cBoxID == null) tBox.Visible = false;
else
{
tBox.ID = cBoxID;
tBox.AutoPostBack = true;
tBox.EnableViewState = true;
ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(tBox);
//tBox.CheckedChanged += new EventHandler(Force_Post_Back);
}
QuickFilter.Attributes["class"] = "quick-filter";
QuickFilter.Attributes["title"] = "Quick Filter";
IconMagnifier.Attributes["class"] = "icon-magnifier";
GridResults.ID = "ltlGridResults";
GridResults.ClientIDMode = ClientIDMode.Static;
//GridResults.EnableViewState = false;
QuickFilter.Controls.Add(IconMagnifier);
GridHeader.Controls.AddAt(0, tBox);
GridHeader.Controls.Add(QuickFilter);
GridHeader.Controls.Add(GridCount);
GridHeader.Controls.Add(GridDescription);
GridItem.Controls.Add(GridHeader);
GridItem.Controls.Add(GridResults);
}
protected void Page_PreRender(object sender, EventArgs e)
{
CreateGrid();
}
protected override void Render(HtmlTextWriter writer)
{
GridItem.RenderControl(writer);
}
Image to generated html
I added the following line of code to the bottom of my CreateGrid method:
this.Controls.Add(GridItem);
This allowed me to add the GridItem control to the current control, thus allowing for post backs. Without this call even though you render the Checkbox, it is completely dumb.
I have a dropdownlist that load all the list items from a text file, it contains a list of printer name,description,ipaddress and connection string id. so I display to the user the printer name-description and when the user selects the printer the values I pass is either the ip address or connection string depending on the situation.
protected void Page_Load(object sender, EventArgs e)
{
LoadPrinterList();
}
protected void LoadPrinterList()
{
string CSVFilePathName =
System.Configuration.ConfigurationManager.AppSettings["FilePath"];
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
//1st row must be column names;
//force lower case to ensure matching later on.
for (int i = 0; i < Cols; i++)
dt.Columns.Add(Fields[i].ToLower(), typeof(string));
dt.Columns.Add("nameanddescription",
typeof(string), "name +'-'+ description");
dt.Columns.Add("ipandconnectionstring",
typeof(string), "ip +'-'+ ConncetionStringID");
DataRow Row;
for (int i = 1; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
Row = dt.NewRow();
for (int f = 0; f < Cols; f++)
Row[f] = Fields[f];
dt.Rows.Add(Row);
}
string hostname = Request.UserHostName.Substring(0, 3);
string[] name = Printerlist.SelectedValue.Split('-');
//string plant = name[0].ToString();
//string plantvalue = plant.Substring(0, 3);
//if(hostname == plantvalue)
//{
Printerlist.DataTextField = "nameanddescription";
Printerlist.DataValueField = "ipandconnectionstring";
//}
Printerlist.DataSource = dt;
Printerlist.DataBind();
}
What the user sees first as an option for the printer list
when the user click the drop down they see this:
when drop down is clicked
so now the user selects a printer so selected index is > 0 so based on that I do the following in code behind.
protected void Printerlist_SelectedIndexChanged(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
else
{
if (Printerlist.SelectedItem.Text.Length > 0)
{
TxtItem.Focus();
}
else
{
TxtItem.Text = string.Empty;
TxtQty.Text = string.Empty;
DropDownList2.SelectedIndex = 0;
lbldesc.Visible = false;
//TxtBase.Text = string.Empty;
//TxtBase1.Text = string.Empty;
bestbeforewillbe.Text = string.Empty;
TxtBestBeforeMonths.Text = string.Empty;
TxtRotcode.Text = string.Empty;
zplcode.Text = string.Empty;
string message = "The selected printer is
not a local printer";
System.Text.StringBuilder sb =
new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock
(this.GetType(), "alert", sb.ToString());
}
}
}
this is the dropdownlist values in my aspx page
<asp:DropDownList ID="Printerlist" runat="server"
Height="16px" Width="268px" AutoPostBack="True" OnSelectedIndexChanged="Printerlist_SelectedIndexChanged" OnTextChanged="Printerlist_TextChanged" ViewStateMode="Enabled"></asp:DropDownList>
I have EnableViewState=true; but that didn't help either.
plese help I cant seem to figure out, every time the user selects a value there is a postback and after the postback "-" is selected as the printer value.
Simply check ISPOSTBACK on page load
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
LoadPrinterList();
}
You need to explicitly check if a PostBack occurred, otherwise any time that your Page_Load method is being triggered, it is repopulating your controls with their initial data (i.e. you are losing your changes there).
You simply need to add an if-statement and only execute your LoadPrinterList() method if it is an initial load :
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// Only perform this on the initial load
LoadPrinterList();
}
}
Additionally, you shouldn't need a similar check within your Printerlist_SelectedIndexChanged event as the event is going to be triggered from within the page (i.e. after it has already been loaded), so that statement should never evaluate as true.
First time poster, long time lurker. I am having some trouble with my ASP.NET page, and I hope someone can help me resolve my issue.
Basically, I have a bunch of checkboxes in a gridview, and two buttons: a 'find' button, and a 'save' button. The 'find' can set the value of the checkbox, but if a user unchecks it, I want to capture that change when the user hits 'save'. Currently, it does not work.
Relevant ASPX:
<%# Page Language="C#" AutoEventWireup="true" EnableViewState="true" CodeBehind="FindTransactions.aspx.cs" Inherits="Basic.FindTransactions" MasterPageFile="~/Trans.Master" %>
Relevant Code Behind here:
Page:
public partial class FindTransactions : System.Web.UI.Page
{
GridView _gridview = new GridView() { ID = "_gridView" };
DataTable _datatable = new DataTable();
Int32 _buyerID = new Int32();
protected void Page_Load(object sender, EventArgs e)
{
}
"Find" button:
protected void Find_Click(object sender, EventArgs e)
{
//truncated
_datatable.Rows.Add(
//filled with other data from a custom object.
);
ViewState["_datatable"] = _datatable;
ViewState["_buyerID"] = _buyerID;
BuildGridView((DataTable)ViewState["_datatable"],(Int32)ViewState["buyerID"]);
}
BuildGridView function:
protected void BuildGridView(DataTable d, Int32 b)
{
_gridview.DataKeyNames = new String[] {"Transaction ID"};
_gridview.AutoGenerateColumns = false;
_gridview.RowDataBound += new GridViewRowEventHandler(OnRowDataBound);
for(Int32 i = 0; i < d.Columns.Count; i++)
{
Boundfield boundfield = new BoundField();
boundfield.DataField = d.Columns[i].ColumnName.ToString();
boundfield.HeaderText = d.Columns[i].ColumnName.ToString();
_gridview.Columns.Add(boundfield);
}
_gridview.DataSource = d;
_gridview.DataBind();
//truncated
Panel1.Controls.Add(_gridview);
}
Row Bound Event handler:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String controlID = "checkBox";
CheckBox c = new CheckBox() { ID = controlID};
c.Enabled = true;
Boolean success;
Boolean v;
success = Boolean.TryParse(e.Row.Cells[8].Text, out v);
e.Row.Cells[8].Controls.Add(c);
if (success)
{
c.Checked = v;
if (c.Checked)
{
//Will uncomment once other things work
//e.Row.Visible = false;
}
}
else
{
c.Checked = false;
}
}
}
All of that works. Here is where it starts to break down:
"Save" button:
protected void Save_Click(object sender, EventArgs e)
{
//Both for troubleshooting and both return 0. (Expected for datatable)
Label1.Text = _gridview.Rows.Count.ToString();
Label2.Text = _datatable.Rows.Count.ToString();
/*truncated
*/
if (grid.Rows.Count == 0)
{
BuildGridView((DataTable)ViewState["infoTable"], (Int32)ViewState["guestID"]);
}
foreach (GridViewRow r in grid.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)r.FindControl("checkBox");
if (cb != null && cb.Checked)
{
//This never seems to modify the label.
//Will put code to modify database here.
Label2.Text += "Hi " + r.RowIndex.ToString();
}
}
}
}
After I hit the save button, PostBack occurs and GridView is empty (Rows.Count is 0). ViewState appears to be lost before I get a chance to loop through the GridView rows to determine the checkbox values.
At the end of it all, I just want to capture the status of those checkboxes, changed by user interaction or not, by hitting the 'Save' button.
I found some other articles, but a lot of them haven't worked when I tried implementing the various fixes.
This one seems to be the closest that describes my issue, and the code is structured similarly, but I don't quite understand how to implement the fix: GridView doesn't remember state between postbacks
[New simplified code to illustrate problem:]
namespace GridViewIssue
{
public partial class GridViewNoMaster : System.Web.UI.Page
{
GridView _gridView = new GridView() { ID = "_gridView" };
DataTable _dataTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Find_Click(object sender, EventArgs e)
{
BuildDataTable();
List<String> list = new List<String>();
list.Add("1");
list.Add("User");
list.Add("10/12/2014");
foreach (String s in list)
{
_dataTable.Rows.Add(
list[0],
list[1],
list[2]
);
}
BuildGridView();
//Feedback.Text = _gridView.Rows.Count.ToString();
}
protected void Save_Click(object sender, EventArgs e)
{
Feedback.Text = "Save Clicked, PostBack: " + IsPostBack + ", GridView Row Count: " + _gridView.Rows.Count + ", GridView ViewState: " + _gridView.EnableViewState;
foreach (GridViewRow r in _gridView.Rows)
{
if(r.RowType == DataControlRowType.DataRow)
{
Feedback.Text = "In DataRow type" + _gridView.Rows.Count;
}
}
}
protected void BuildDataTable()
{
_dataTable.Columns.Add("Transaction ID", typeof(String));
_dataTable.Columns.Add("Name", typeof(String));
_dataTable.Columns.Add("Date", typeof(String));
}
protected void BuildGridView()
{
for (Int32 i = 0; i < _dataTable.Columns.Count; i++)
{
BoundField b = new BoundField();
b.DataField = _dataTable.Columns[i].ColumnName.ToString();
b.HeaderText = _dataTable.Columns[i].ColumnName.ToString();
_gridView.Columns.Add(b);
}
_gridView.DataKeyNames = new String[] { "Transaction ID" };
_gridView.AutoGenerateColumns = false;
_gridView.DataSource = _dataTable;
_gridView.DataBind();
Panel1.Controls.Add(_gridView);
}
}
}
Here i am updating the gridview value but the value is not updating..TextBox txtID,TextBox txtName,TextBox txtAge retains the older value only and the value is not getting updated..Can anyone tel me like what am i doing wrong here
Here is my code
protected void gvTemp_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
int autoid = Int32.Parse(gvTemp.DataKeys[e.RowIndex].Value.ToString());
int id = Convert.ToInt32(gvTemp.DataKeys[e.RowIndex].Values[0].ToString());
activeTabIndex = Convert.ToInt16(Session["activeTabIndex"]);
TextBox txtID = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtId"));
TextBox txtName = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtName");
TextBox txtAge = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtAge");
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["ID"] = txtID.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Name"] = txtName.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Age"] = txtAge.Text;
gvTemp.DataSource = dataSetInSession.Tables["Days" + activeTabIndex.ToString()];
gvTemp.DataBind();
gvTemp.EditIndex = -1;
}
and
private void CreateDataSkeletton(int intTabIndex)
{
dataSetInSession = new DataSet();
Session["intTabIndex"] = intTabIndex;
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (dataSetInSession.Tables["Days" + intTabIndex].Rows.Count > 0)
{
gvTemp.DataSource = dataSetInSession.Tables["Days" + intTabIndex];
gvTemp.DataBind();
}
else
{
gvTemp.DataSource = dataSetInSession.Tables["Days"];
gvTemp.DataBind();
}
temp.Controls.Add(gvTemp);
}
Any suggestion??
EDIT(1):
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDataTable();
}
dataSetInSession = new DataSet();
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (Session["dynamicTabIDs"] != null)
{
//if dynamicTabIDs are in session, recreating the Tabs
//that are associated with the Tab IDs
//and adding them to the TabContainer that will contain
//all of the dynamic tabs.
//retrieving the tab IDs from session:
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
if (TabContainerContent.ActiveTabIndex == -1)
{
TabContainerContent.ActiveTabIndex = Convert.ToInt16(Session["intTabIndex"]);
}
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
//looping through each TabID in session
//and recreating the TabPanel that is associated with that tabID
foreach (string tabID in dynamicTabIDs)
{
//creating a new TabPanel that is associated with the TabID
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
//TabContainerContent.ActiveTabIndex = tab;
//Setting the ID property of the TabPanel
tab.ID = tabID;
//setting the TabPanel's HeaderText
tab.HeaderText = "Days " + (TabContainerContent.Tabs.Count + 1).ToString();
//creating a Label to add to the TabPanel...at this point you'll have to
//create whatever controls are required for the tab...
Label tabContent = new Label();
//Giving the Label an ID
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
//Setting the Label's text
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
//Adding the Label to the TabPanel
tab.Controls.Add(tabContent);
//Adding the TabPanel to the TabContainer that contains the dynamic tabs
TabContainerContent.Tabs.Add(tab);
}
}
else
{ //Creating a new list of dynamicTabIDs because one doesn't exist yet in session.
dynamicTabIDs = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Read Page Life Cycle
And you will get, that if you want to bind in code-behind, you should do it in Init Event, other wise there are no events will fire.
It seems to be Page.IsPostback problem.Need to add Page.IsPostback property in your page_load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Put your code inside that.
}
}
Actually your control is getting new value but when you click for updation then it calls old value from page_load.So try to put Page.IsPostback into your page_load event,Just like i mentioned.
I hope it helps.
I realy need help for this. I am using AjaxControlToolkit.TabContainer and using ASP.NET Framework 4.0. Gridview,textbox and button are placed in TabContainer on asp page. When I press button postback does happen but its not binding gridview to datatable and textbox contents are also not updated.
I debug the code and found when i press button postback does happen and content does fill up in gridview and textbox value also assigned with new value. but values doesnt display on the page. I dont know why its happening. please help.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ListBoxCustomer.Items.Count != 0)
{
int[] _selectedItems = ListBoxCustomer.GetSelectedIndices();
string _comma = "";
string _custID = "";
InitializeConnection();
if (_selectedItems.Length != 0)
{
foreach (int i in _selectedItems)
{
_custID = _custID + _comma + ListBoxCustomer.Items[i].Value;
_comma = ",";
}
if (custObj != null)
{
//DataTable _dt = new DataTable();
DataSet _ds = new DataSet();
GridViewCustomer.Visible = true;
GridViewCustomer.AutoGenerateColumns = true;
_ds = custObj.GetSelectedCustomers(1, _custID);
GridViewCustomer.DataSource = _ds.Tables[0];
GridViewCustomer.DataBind();
TextBoxTest.Text = GridViewCustomer.Rows.Count.ToString();
TextBoxTest.Text = "test";
}
}
}
}
}
thanks.
Perhaps the DataBind code is never being reached. Have you set some breakpoints to make sure the if-statements aren't blocking you? That is... Is ListBoxCustomer.Items.Count definitely not zero... Is custObj definitely not null?
Where do you assign a value to custObj?