asp.net dynamically button with event handler wont work - javascript

Hi I create button to fire event when user click on row.
It works when I create that "hidden" buttons on master page but when I create those buttons on MainContent it won't fire the event:
List<Button> btnCollection = new List<Button>();
protected void OnRowTask(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CellValue = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "id"));
string urlAddress = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "url_address"));
Button dummyBtn= new Button();
dummyBtn.Attributes["style"] = "display:none;";
dummyBtn.ID = "divBtn_" + CellValue;
dummyBtn.Text = urlAddress;
dummyBtn.Click += new EventHandler(this.rowButton_Click);
PlaceHolderForHiddenBtn2.Controls.Add(dummyBtn);
btnCollection.Add(divButton);
e.Row.Attributes.Add("onclick", "return rowclick(" + CellValue + ");");
}
Session["hiddenBtnCollectionTask"] = btnCollection;
}
Click event:
private void rowButton_Click(object sender, EventArgs e)
{
//some code to exectute
}
On page load I create the same buttons what was added on row created event:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["hiddenBtnCollectionTask"] != null)
{
List<Button> btnGenerateList = (List<Button>)Session["hiddenBtnCollectionTask"];
foreach (Button btn in btnGenerateList)
{
PlaceHolderForHiddenBtn2.Controls.Add(btn);
}
}
}
And JS function that should fire button.click() - event :
function rowclick(id) {
var button = document.getElementById('MainContent_divBtn_' + id);
button.click();
return false;
}
Any ideas?

Related

Execute command only after executing the javascript function

I have a button inside a repeater, and this is the event:
protected void Delete_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
string id = btn.CommandArgument;
string client = "011";
try
{ //When is done
ScriptManager.RegisterStartupScript(this, GetType(), "del", "Del(" + id + ");", true);
//do it
this.Repeater.DataSource = dal.GetT(client);
this.Repeater.DataBind();
}
catch { }
}
I need to update the repeater, only after executing the javascript function Del(id)
How can this be done in the best way?

Load an ASP Website retrieve and redirect a href in C#

I am doing my first add-in Outlook. I want to load an ASP website in a Form and redirect with the href which is in a <li> tag. There is no specific id to identify only the value of the <span>. See below. Thank's in advance.
<li class="rmItem ">
<a class="rmLink rmSelected" style="width: 194px;" href="javascript:Goto('DM_NEW_OBJECT.ASPX?DM_CAT_ID=2171&DM_PARENT_ID=254769&INPUTSELECTION=&DM_OBJECT_ID=0&PACK_ID=0&CASE_ID=0&mode=0&SITE=Default');">
<span class="rmText">Dossier protection</span>
</a>
</li>
You could attach yourself to the DocumentCompleted event, it triggers when the document is fully loaded and then you can search the DOM in a similar way.
First you add an event handler to your DocumentCompleted event inside your Constructor, and remove your event handler when the Form closes.
On the load event, you can navigate to the wanted page, and then search the DOM for all li's, and then check for the text you want. If it matches, search for the URL's and then invoke the click event (which would trigger your javascript Goto function).
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += OnPageCompleted;
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate(Path.Combine(Environment.CurrentDirectory, "DemoPage.html"));
}
protected virtual void OnPageCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Document == null)
{
return;
}
if (webBrowser1.Document.Body == null)
{
return;
}
HtmlElementCollection col = webBrowser1.Document.Body.GetElementsByTagName("li");
if (col == null || col.Count == 0)
{
return;
}
foreach (HtmlElement elem in col)
{
if (elem == null || string.IsNullOrWhiteSpace(elem.InnerHtml))
{
continue;
}
var links = elem.GetElementsByTagName("a");
if (links == null || links.Count == 0)
{
continue;
}
foreach (HtmlElement url in links)
{
if (url == null || string.IsNullOrWhiteSpace(url.InnerHtml))
{
continue;
}
try
{
url.InvokeMember("click");
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().FullName + "\r\n" + ex.Message);
}
}
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
webBrowser1.DocumentCompleted -= OnPageCompleted;
}
}

Dropdownlist "Enable true" is not working Asp.net

I have set dropdown enable set to false in one button click and i will set enable="true" is not working in page load
here is my aspx
<asp:DropDownList ID="ddlJournal" runat="server" OnSelectedIndexChanged="ddlJournal_SelectionChanged" AutoPostBack="true" CssClass="drop" />
Here is my click event:
protected void btnTemplate_click(object sender, EventArgs e)
{
check.Value = "1";
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Load_functions()", true);
//txtAddJournal.Attributes.Add("Style", "display:block");
//btnUpload.Attributes.Add("Style", "display:block");
//if (fileuploader.HasFile)
//{
try
{
string Filename = Path.GetFileName(fileuploader.FileName);
//fileuploader.SaveAs(Server.MapPath("~/") + Filename);
// fileuploader.SaveAs(Server.MapPath("D:\\Req Sep16\\") + Filename);
OleDbConnection myconnectionini = default(OleDbConnection);
OleDbDataAdapter mycommandini = default(OleDbDataAdapter);
//if (fileuploader.PostedFile.FileName.EndsWith(".xls") == false & fileuploader.PostedFile.FileName.EndsWith(".xlsx") == false)
//{
// // lbl_Error.Text = "Upload only excel format";
// Response.Write(#"<script language='javascript'>alert('Upload only excel format');</script>");
// return;
//}
//else
//{
gvDetails.DataSource = null;
string pathToSave = HttpContext.Current.Server.MapPath("~/UploadFiles/") + "Copy of Database_HBM";
//fileuploader.PostedFile.SaveAs(pathToSave);
//strFilePath = "D:\\Files\\" + fileuploader.FileName;
string constrini = "provider=Microsoft.Jet.OLEDB.4.0;data source=" + pathToSave + ";Extended Properties=Excel 8.0;";
DataSet ds = new DataSet();
// DataTable dt = new DataTable();
myconnectionini = new OleDbConnection(constrini);
mycommandini = new OleDbDataAdapter("select * from [Sheet1$]", myconnectionini);
ds = new DataSet();
mycommandini.Fill(ds);
gvDetails.DataSource = ds.Tables[0];
gvDetails.DataBind();
ddlJournal.SelectedIndex = -1;
ddlJournal.Enabled = false;
//ddlJournal.Attributes.Add("disabled", "disabled");
//}
}
catch (Exception ex)
{
string msg = ex.Message;
}
//}
}
And my page load event is
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Grid", "headerLock();", true);
// ScriptManager.RegisterStartupScript(Page, this.GetType(), "Key", "<script>headerLock();</script>", true );
if (!IsPostBack)
{
Bindddl();
BindGrid(null);
ddlJournal.Enabled = true;
}
else
{
ddlJournal.Enabled = true;
}
}
button :
<asp:Button ID="btnUpload" runat="server" Text="Template 1" OnClientClick="return Validate();"
OnClick="btnTemplate_click" CssClass="btn" />
but still my dropdown list is disable.
suggest me get a solution
thanks in advance
You can set dropdown list Enabled false from its control only like this
<asp:DropDownList ID="ddlJournal" runat="server" OnSelectedIndexChanged="ddlJournal_SelectionChanged" AutoPostBack="true" CssClass="drop" Enabled="false"/>
And the rest code should work fine.
Please mark it helps
Understand that your if-else condition in Page_Load() method is the main culprit. You're always setting ddlJournal.Enabled = true, no matter what. Seems like you didn't properly understand the concept of IsPostBack. ddlJournal is supposed to be disabled when IsPostBack is true, because that's what you want. Otherwise, it's supposed be enabled.
This is a very concise explanation about what IsPostBack is:
Postback in an event that is triggered when a action is performed by a contol on a asp.net page. for eg. when you click on a button the data on the page is posted back to the server for processing.IsPostback is normally used on page _load event to detect if the page is getting generated due to postback requested by a control on the page or if the page is getting loaded for the first time.
[a comment from http://forums.asp.net/t/1115866.aspx?What+is+IsPostBack ]
So based on that, you should change your code like the following:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Grid", "headerLock();", true);
if (!IsPostBack)
{
//When IsPostBack is false, ddlJournal should be enabled
Bindddl();
BindGrid(null);
ddlJournal.Enabled = true;
}
else
{
//Else, IsPostBack is true, so, ddlJournal should be disabled
ddlJournal.Enabled = false;
}
}
Also, you don't need this in your btnTemplate_click() method since you're doing this on page load:
ddlJournal.Enabled = false;

Change Gridview Textbox's visible property true false on DropdownLists's Selected index change event using javascript not working

I am making Gridview's Textbox visible true or false when user changes Dropdownlists selectedIndexchange event for that i have done following code
My .CS File code is as below:
protected void gvTaskList_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField hdn = (HiddenField)e.Row.FindControl("hdnStatus");
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlStatus");
TextBox txt = (TextBox)e.Row.FindControl("txtVal");
if (ddl != null)
{
ddl.Items.Add("Not Started");
ddl.Items.Add("In Progress");
ddl.Items.Add("Complete");
if (hdn != null)
{
ddl.SelectedValue = hdn.Value;
}
//ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
ddl.Attributes.Add("onChange", "return myFun(" + "'" + txt.ClientID + "'" +");");
}
}
}
catch (Exception ex)
{
Utility.ErrorList("EmpTaskList--RowdataBound", ex.ToString());
}
}
Note: My combobox and textbox both are in EditTmplate
Javascript code is as below
<script type="text/javascript">
function myFun(txtControl) {
var v = document.getElementById("<%=" + txtControl + "%>");
alert(v);
}
When i m changing dropdownlist index function is called and alert is showing null.
So can anyone please suggest me what i m doing wrong??
I don't think you want the server-side tags in your getElementById call:
var v = document.getElementById(txtControl);

How to programatically change selected item in dropdown while javascript onchange applied asp.net

i have two dropdowns and thier hidden field each on codebehind im adding javascript onchange event by attribute.add and a button to perform some dynamic actions like adding controls at runtime
when i click that button dropdown are reset. In order to maintain state i have a hidden field with dropdown i get selectedvalue from hidden field but by coding DDCity.Items.FindByValue doesnt seems to work Can anyone help?
protected void Page_Load(object sender, EventArgs e)
{ DDCountry.Attributes.Add("onChange", "javascript:BufferAddDDCountry('" + DDCountry.ClientID + "');");
DDCity.Attributes.Add("onChange", "javascript:BufferAddDDCity('" + DDCity.ClientID + "');");}
if (hiddenDDCityValue.Text != "0")
{
DDCity.Items.FindByValue(hiddenDDCityValue.Text).Selected = true;// this dont work
}
if (!IsPostBack)
{ this.populateCountry();populateCity();}
javascript code
<script type="text/javascript">
function BufferAddDDCountry(objDd) {
try {
var objHidden = document.getElementById('hiddenDDcountryValue');
objHidden.value = document.getElementById(objDd).value;
} catch (e) {
alert(e);
}
};
function BufferAddDDCity(objDd) {
try {
var objHidden = document.getElementById('hiddenDDCityValue');
objHidden.value = document.getElementById(objDd).value;
} catch (e) {
alert(e);
}
};
</script>
i atlast made it working in javascript hope this will help others here is the code
codebehind pageload
ScriptManager.RegisterStartupScript(UpdatePanel, this.GetType(), "Dropdownselectedvaluechange", "javascript:setSelectedValue('" + DDCity.ClientID + "','" + hiddenDDCityValue.Text + "');", true);
javascript code
function setSelectedValue(dropdownList, selectedValue) {
var dropdown = document.getElementById(dropdownList);
for (var i = 0; i < dropdown.options.length; i++) {
if (dropdown.options[i].value == selectedValue) {
dropdown.options[i].value = selectedValue;
dropdown.options[i].selected = true;
break;
}
}
return;
}

Categories

Resources