DropDownlist PostBack Looses Selected Value - c#

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.

Related

Retrieve value from dynamic dropdownlist in placeholder C#

I have dynamic drop down lists that are created based on what's selected in the list box.. When clicking confirm this is when the drop down lists are created. Clicking save is where I attempt to retrieve the values. However I am unable to retrieve that values that are in the drop down lists.
Code:
protected void btnConfirm_Click(object sender, EventArgs e)
{
int ID = 0;
foreach (string value in values)
{
MyStaticValues.alEdit.Add(value);
CreateEditForm(value, ID);
ID += 1;
}
if (values.count != 0)
{
btnSave.Visible = true;
btnConfirm.Enabled = false;
}
}//End of btnConfirm_Click
protected void CreateEditForm(string Value, int ID)
{//Creates an edit form for the value inserted.
string name = value;
//This part adds a header
phEditInventory.Controls.Add(new LiteralControl("<h2>" + name + "</h2>"));
phEditInventory.Controls.Add(new LiteralControl("<div class=\"clearfix\"></div>"));
//Create a label
Label lblName = new Label();
lblName.Text = "Name";
lblName.ID = "lblName" + ID;
lblName.CssClass = "control-label";
//Create a Drop Down List
DropDownList ddlName = new DropDownList();
ddlName.ID = "ddlName" + ID;
ddlName.CssClass = "form-control";
//Set default N/A Values For Drop Down List
ddlName.Items.Add(new ListItem("N/A", Convert.ToString("0")));
//The Rest of the Values are populated with the database
//Adds the controls to the placeholder
phEditInventory.Controls.Add(lblName);
phEditInventory.Controls.Add(ddlName);
phEditInventory.Controls.Add(new LiteralControl("<div class=\"clearfix\"></div>"));
} //End of CreateEditForm
protected void btnSave_Click(object sender, EventArgs e)
{
string name = "";
try
{
for (int i = 0; i < MyStaticValues.alEdit.Count; i++)
{
string nameID = "ddlName" + i.ToString();
DropDownList ddlName = (DropDownList)phEditInventory.FindControl(nameID);
name = ddlName.SelectedValue.ToString();
}
}
catch (Exception ex)
{
}
phEditInventory.Visible = false;
btnSave.Visible = false;
MyStaticValues.alEdit.Clear();
}//End of btnSave_Click Function
Your problem is that the dynamically created dropdown lists are not maintained on postback. When you click the Save button, a postback occurs, and the page is re-rendered without the dynamically created dropdowns. This link may help.
Maintain the state of dynamically added user control on postback?

'Find and Save' functionality not working

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);
}
}
}

get code behind checkboxes in postback

I want to add some checkboxes at the beginning of every row in a table in the page_load: (I add them in a asp:placeholder)
protected void Page_Load(object sender, EventArgs e)
{
Table dtTable = new Table();
TableHeaderRow dtHeaderRow = new TableHeaderRow();
TableHeaderCell dtHeaderCheckbox = new TableHeaderCell();
dtHeaderCheckbox.Controls.Add(dtHeaderCkBox);
dtHeaderRow.Cells.Add(dtHeaderCheckbox);
foreach (DataColumn col in _ds.Tables[0].Columns)
{
TableHeaderCell dtHeaderCell = new TableHeaderCell();
dtHeaderCell.Text += col.ColumnName;
dtHeaderRow.Cells.Add(dtHeaderCell);
}
dtTable.Rows.Add(dtHeaderRow);
TableRow row;
for (int i = 0; i < _ds.Tables[0].Rows.Count; i++)
{
row = new TableRow();
TableCell dtCell = new TableCell();
CheckBox ckBox = new CheckBox();
ckBox.ID = "chkBox_" + _ds.Tables[0].Rows[i]["IDENTIFIER"].ToString();
ckBox.AutoPostBack = false;
ckBox.EnableViewState = false;
dtCell.Controls.Add(ckBox);
row.Cells.Add(dtCell);
for (int j = 0; j < _ds.Tables[0].Columns.Count; j++)
{
TableCell cell = new TableCell();
cell.Text = _ds.Tables[0].Rows[i][j].ToString();
row.Cells.Add(cell);
}
dtTable.Rows.Add(row);
}
phUnconfirmedDiv.Controls.Add(dtTable);
}
The problem is now, when the user press a submit button(and postback), I don't have access to my checkboxes:
protected void btnAccept_OnClick(object sender, EventArgs e)
{
List<CheckBox> chkList = new List<CheckBox>();
foreach (Control ctl in form1.Controls)
{
if (ctl is CheckBox)
{
if (ctl.ID.IndexOf("chkBox_") == 0)
{
chkList.Add((CheckBox)ctl);
}
}
}
ScriptManager.RegisterStartupScript(this, GetType(), "event", "alert('" + chkList.Count + "');", true);
}
Dynamically generated controls lost their state once they are rendered on view. And for you, to access them again in your code-behind, when your postbacks, you will have to re-create them and after that you will be able to manipulate them.
As far as getting the checked values of the checkboxes is concerned, you could try something like this. This might not be exact, should give an idea though.
This would be your check-box :
<input type="checkbox" id="yourId" name="selectedIds" value="someValue"/>
In your codebehind :
value = Request.Form["selectedIds"];
Hope this helps.
I now managed to solve this problem. Thanks all for your tips!
All checkboxes that are checked are sent through the postback. So the "easiest" way is to search for all parameters, sent in postback, that are beginning like "chkBox_" and then save them in a list/array. So I know which data should be updated in my database:
protected void btnAccept_OnClick(object sender, EventArgs e)
{
List<String> chkList = new List<String>();
// All checked checkboxes are sent via the postback. Save this parameters in a list:
foreach (string s in Request.Params.Keys)
{
if (s.ToString().IndexOf("chkBox_") == 0)
{
chkList.Add(s.ToString());
}
}
Is autopostback set to true on the user interface controls for the button? ei:
<telerik:RadButton runat="server" ID="rBtnRelease" Text="Release" Width="100px" OnClick="rBtnRelease_Click" AutoPostBack="False"/>
That's usually the common mistake when one tries to get data back and forth between the client and the server side.

Gridview Edit/Update is not working?

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.

CheckChanged event called when trying to switch to another TAB?

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.

Categories