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.
Related
I got two comboxBox with SelectedIndexChanged event enabled.
In the comboBox2 i want to change the SelectedValue of comboBox1, and that works, but the SelectedIndexChanged of comboBox1 is always triggered even i explicit disabled that.
And the code in selectedIndexChange of the ComboBox1 overwrite what I do in the ComboBox2, that the problem.
I've tried hundreds ways to avoid that but anything works, the event always occurs.
Bellow is my code of ComboBox1:
private void cmbBeneficiario_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cb = (ComboBox)sender;
if (!cb.Focused)
{
return;
}
systemChange = true;
if (cnpjChange)
{
if (!string.IsNullOrWhiteSpace(cmbBeneficiario.Text) &&
!string.IsNullOrWhiteSpace(cmbBeneficiario.Text))
{
var beneficiarioApoliceBeneficiario =
averbacaoController.GetApoliceBeneficiario(cmbBeneficiario.Text);
var apolices = beneficiarioApoliceBeneficiario.Select(x => x.numero_apolice).ToList();
cmbApolice.DataSource = apolices;
cmbApolice.DisplayMember = "numero_apolice";
cmbApolice.Invalidate();
Refresh();
cmbApolice_SelectedIndexChanged(this, e);
var listBene = beneficiariosList;
var filteredList = listBene.Where(x => x.nome_beneficiario == cmbBeneficiario.Text).ToList();
cbbCNPJBeneAverb.DisplayMember = "cnpj_beneficiario";
cbbCNPJBeneAverb.DataSource = filteredList;
}
CarregaBeneficiarioPerfil();
systemChange = false;
}
}
The comboBox2 code (note that I disabled the event of combobox1):
private void cbbCNPJBeneAverb_SelectedIndexChanged(object sender, EventArgs e)
{
cnpjChange = true;
ComboBox cb = (ComboBox)sender;
if (!cb.Focused)
{
return;
}
Console.WriteLine($#"Old ID {cmbBeneficiario.SelectedValue}");
var beneficiario = averbacaoController.GetBeneficarioByCNPJ(cbbCNPJBeneAverb.Text, cmbBeneficiario.Text);
cmbBeneficiario.SelectedIndexChanged -= new EventHandler(cmbBeneficiario_SelectedIndexChanged);
if (cbbCNPJBeneAverb.SelectedIndex > -1)
{
cmbBeneficiario.SelectedValue = beneficiario.id_beneficiario;
CarregaBeneficiarioPerfil();
}
Console.WriteLine($#"New ID {cmbBeneficiario.SelectedValue}");
Console.WriteLine($#"Tinha que ser o ID {beneficiario.id_beneficiario}");
cmbBeneficiario.SelectedIndexChanged += new EventHandler(cmbBeneficiario_SelectedIndexChanged);
cnpjChange = false;
}
Printscreen of my debug:
As my comments above, you can use a class-scope variable to do check:
Add a temporary class-scope variable:
private bool cb1EventIgnore = false;
Set it to ture/false in cbbCNPJBeneAverb_SelectedIndexChanged:
if (cbbCNPJBeneAverb.SelectedIndex > -1)
{
cb1EventIgnore = true;
cmbBeneficiario.SelectedValue = beneficiario.id_beneficiario;
CarregaBeneficiarioPerfil();
cb1EventIgnore = false;
}
Check the value cb1EventIgnore in cmbBeneficiario_SelectedIndexChanged at the beginning:
private void cmbBeneficiario_SelectedIndexChanged(object sender, EventArgs e)
{
if(cb1EventIgnore) return;
//your codes here
}
After a lot of attempts, bellow are the piece of code that solved my question:
cmbBeneficiario.Enabled = false;
Simple like this, i dont know why c# was not able to not trigger the event even I explicit told him to.
I'm reading a list of id numbers from a database table into a placeholder textbox but however; if I do a button click the data is removed.
protected void btnSearch_Click(object sender, EventArgs e)
{
while (myReader.Read())
{
TextBox txt = new TextBox();
txt.Text = (string)myReader["idNumber"];
txt.ID = "txt" + i;
txt.ReadOnly = true;
ContentPlaceHolder1.Controls.Add(txt);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
i++;
}
}
This is a common problem when working with dynamically added controls in web forms (especially if you're coming from a winforms background). Pages in ASP.NET Web Forms are stateless, and reconstructed on each postback. Therefore, if you add a control to a page during a server event, you'll also have to add it to the page on subsequent Page loads if you want it to appear. You can accomplish this with something similar to the following:
protected List<Control> ControlCache
{
get => (List<Control>)(Session["cachedControlsForPageX"] = (Session["cachedControlsForPageX"] as List<Control>) ?? new List<Control>());
set => Session["cachedControlsForPageX"] = value;
}
/* If you can't use C# 7's expression bodied property accessors, here's the equivalent in blocks:
protected List<Control> ControlCache
{
get { return (List<Control>)(Session["cachedControlsForPageX"] = (Session["cachedControlsForPageX"] as List<Control>) ?? new List<Control>()); }
set { Session["cachedControlsForPageX"] = value; }
}
*/
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
foreach (var control in ControlCache)
{
ContentPlaceHolder1.Controls.Add(control);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
}
}
else
ControlCache = null;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
while (myReader.Read())
{
TextBox txt = new TextBox();
txt.Text = (string)myReader["idNumber"];
txt.ID = "txt" + i;
txt.ReadOnly = true;
ContentPlaceHolder1.Controls.Add(txt);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
ControlCache.Add(txt);
i++;
}
}
I have a gridview control wherein I have added textbox in coloumn 5 & 6 dynamically from server side code as below:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.TextBox txtFrom = new System.Web.UI.WebControls.TextBox();
txtFrom.ID = "txtFrom";
txtFrom.Width = 70;
txtFrom.AutoPostBack = true;
txtFrom.TextChanged += new System.EventHandler(this.txtFrom_Changed);
e.Row.Cells[5].Controls.Add(txtFrom);
System.Web.UI.WebControls.TextBox txtTo = new System.Web.UI.WebControls.TextBox();
txtTo.ID = "txtTo";
txtTo.Width = 70;
txtTo.AutoPostBack = true;
txtTo.TextChanged += new System.EventHandler(this.txtTo_Changed);
e.Row.Cells[6].Controls.Add(txtTo);
}
}
However when I am calling the Textchanged event (code shown below), the textboxes are disappearing.
protected void txtTo_Changed(object sender, EventArgs e)
{
System.Web.UI.WebControls.TextBox textbox = (sender as System.Web.UI.WebControls.TextBox);
MyAlert(textbox.ID + " text changed value: " + textbox.Text);
}
Request you to suggest why this is happening and how can I solve this.
Thanking you all in anticipation.
Thanks. I could solve the issue by modifying the code as below and calling the new function during postback.
protected void getDateControls()
{
foreach (GridViewRow grow in gdView.Rows)
{
System.Web.UI.WebControls.TextBox txtFrom = new System.Web.UI.WebControls.TextBox();
txtFrom.ID = "txtFrom";
txtFrom.Width = 70;
txtFrom.AutoPostBack = true;
txtFrom.TextChanged += new System.EventHandler(this.txtFrom_Changed);
grow.Cells[5].Controls.Add(txtFrom);
System.Web.UI.WebControls.TextBox txtTo = new System.Web.UI.WebControls.TextBox();
txtTo.ID = "txtTo";
txtTo.Width = 70;
txtTo.AutoPostBack = true;
txtTo.TextChanged += new System.EventHandler(this.txtTo_Changed);
grow.Cells[6].Controls.Add(txtTo);
}
}
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.
I'm currently working on an app that technically interacts with an html page that uses dynamic content.
My problem is when I try to append data to the WBC the content isn't updating correctly.
namespace CheckList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
.... code removed ....
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != null)
{
HtmlDocument doc = webBrowser1.Document;
HtmlElement row = doc.CreateElement("tr");
HtmlElement cell1 = doc.CreateElement("td");
HtmlElement cell2 = doc.CreateElement("td");
cell1.InnerHtml = "[X] " + textBox1.Text;
cell2.SetAttribute("class", "solved_2");
cell2.InnerHtml = "Unsolved";
row.AppendChild(cell1);
row.AppendChild(cell2);
doc.GetElementsByTagName("table")[0].AppendChild(row);
//doc.Write(doc.GetElementsByTagName("HTML")[0].OuterHtml);
webBrowser1.Document.Body.InnerHtml = doc.Body.InnerHtml;
}
}
}
}
What currently happens is, I click "add" it should add the html to the page and update and the javascript and what not should still load.
What happens is it adds the content, but the javascript doesn't work after I attempt to reload the content. The CSS stays in tact though, and the javascript isn't working after that point.
JS Source:
var showalert = true;
var file = "file:///C:/Users/Removed/Documents/Visual Studio 2010/Projects/CheckList/CheckList/bin/Release/";
initiate_instance();
function initiate_instance() {
//insert
$.get(file + "saved.html", function(data) {
//$("table#items").append("<tr><th width='70%'>Issue</th><th width='30%' class='right'>Solved</th></tr>");
$("table#items").html($("table#items").html() + data);
});
//change [X] into a link
$("table#items tr td").each(function() {
$(this).html($(this).html().replace("[X]", "<a onclick='return remove(this)' href='#'>[X]</a>"));
});
//change the css
$("table#items tr:odd").attr("class", "odd");
$("table#items tr td:eq(0)").attr("width", "70%");
$("table#items tr td:eq(1)").attr("width", "30%");
$("td.solved, td.solved_2").click(function() {
if($(this).attr("class") == "solved") {
$(this).attr("class", "solved_2");
$(this).text("Unsolved");
} else {
$(this).attr("class", "solved");
$(this).text("Solved");
}
if(showalert == true) {
alert("Remember, for these changes to keep effect please save before closing the program.");
showalert = false;
}
});
}
//delete rows
function remove(obj) {
if(showalert == true) {
alert("Remember, for these changes to keep effect please save before closing the program.");
showalert = false;
}
$(obj).parent().parent().remove();
return false;
}
TL;DR: Have you tried setting "AllowNavigation" to true?
If you need to prevent navigation, but still need to update the page, a method I've found that works requires:
Initializing the WebBrowser control's DocumentText property with empty HTML to initialize the internal objects (i.e.: Document, DomDocument, Document.Body, etc)
Allowing navigation and the revoking upon page completion (if needed)
Code:
namespace CheckList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Initialize all the document objects
webBrowser1.DocumentText = #"<html></html>";
// Add the Document Completed event handler to turn off navigation
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Load default information via LoadHtml(string html);
LoadHtml(#"<html><head></head><body>Text!<script type='text/javascript' language='javascript'>alert('Aha!');</script></body></html>");
}
private void LoadHtml(string html)
{
webBrowser1.AllowNavigation = true;
// This will trigger a Document Completed event
webBrowser1.DocumentText = html;
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Prevent further navigation
webBrowser1.AllowNavigation = false;
// Clean-up the handler if no longer needed
}
private void button2_Click(object sender, EventArgs e)
{
// Do your document building
LoadHtml(doc.Body.Parent.OuterHtml);
}
}
}
I've found doing it this way:
Prevents users from navigating until allowed
Allows execution of JavaScript (immediately before OnDocumentCompleted fires)