How do i close child window in asp.net c#? - javascript

I am now creating a web site with webforms in C#. I made a button that opens the child window with a landscape photo if pressed. On top of the landscape painting in the child window, comments written in the parent window are displayed.
The user can press this button to open as many child windows as they press, separate from the ASPX page with this button. Just press the button 10 times to open 10 pages of child windows with pictures of landscape paintings.
What I want to do is not press the button 10 times to create 10 child windows, but I want to update the child window 9 times after the child window is created in the first time.
If possible, I'd like you to tell me how to do it. Also, I thought that it would be difficult for me to do so, so I thought that if I pressed the button after the second time, the old child window created by pressing the button before that would close and a new child window would be born.
Below is the code I wrote.
↓aspx
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
↓aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string url=string.Format("WebForm1.aspx?q={0:s}",TextBox1.Text);
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "OpenNewWindow", "window.open('" + url + "', null);",true);
}
The problem is twofold. One way is to update the child window. The other way is to close the child window. I thought that the line window would be closed with the code below, so I tried it lightly, but the parent window closed and the child window remained.
↓aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
string url=string.Format("WebForm1.aspx?q={0:s}",TextBox1.Text);
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "CloseNewWindow", "window.Close('" + url + "', null);",true);
}
What should I do?

I think you best consider having this pop up appear on the CURRENT page.
And now that you want to restrict to "one", then that makes this a WHOLE lot less work.
There are more "dialog" systems then flavors of ice cream to choose from.
but, the two most common are the bootstrap ones, and the one from jQuery.UI.
I find the jQuery.UI VERY easy to work with - and you can control position with much greater ease then bootstrap ones.
And given that you have a SUPER high chance of already having jQuery, then adopting jQuery.UI from the same folks makes all the more sense.
And jQuery.UI dialogs can be "modal", and that means focus can't get out of the dialog until you "ok" or "save" or whatever.
So, lets take a simple GridView. Say we have some rows, and a "image".
When we click on the edit button, we pop a dialog with the picture, and also allow you to edit the comments.
So, our Grid is say this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:BoundField DataField="Fighter" HeaderText="Fighter" />
<asp:BoundField DataField="Engine" HeaderText="Engine" />
<asp:BoundField DataField="Thrust" HeaderText="Thrust" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:ImageButton ID="cmdView" runat="server" Width="150px"
ImageUrl = '<%# Eval("ImagePath") %>'
OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code on page load is thus this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Fighters");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
And now we have this:
So, the way jQuery.UI works?
You create a simple "div" on the same page, and it will become your "dialog"
You then hide with style=display:none.
So our markup for this "div" to disaplay the picture "big" and edit comments is this
(we drop it below the GV)
So, we have this simple markup to display picture, and let user edit comments for the picture:
<div id="EditOne" runat="server" style="text-align:center;display:none" clientidmode="static">
<br />
<asp:Image ID="Image1" runat="server" width="90%" />
<br />
<h4>Edit Description</h4>
<asp:TextBox ID="txtDescription" runat="server"
TextMode="MultiLine" Columns="90" Height="100px">
</asp:TextBox>
<br />
</div>
<asp:Button ID="cmdSave" runat="server" Text="Save" ClientIDMode="Static"
style="display:none" OnClick="cmdSave_Click"/>
Note careful in above - right below the div, I have a hidden save button.
So, now the jQuery routine that we pop to display this div as a dialog:
this:
<script>
function popimage(btn) {
pWidth = "50%"
myDialog = $("#EditOne");
myDialog.dialog({
title: "Edit Comments",
modal: true,
width: pWidth,
closeText: "",
show: "fade",
buttons: {
Save: function () {
myDialog.dialog("close")
$('#cmdSave').click()
},
Cancel: function () {
myDialog.dialog("close")
}
}
})
}
</script>
So, now we only need our button row click from the grid (I used image button).
That code is this:
We get the current row PK id, pull from database, and fill out the "div", and then pop it:
protected void cmdView_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM Fighters WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PK;
DataTable rstFighter = MyRstP(cmdSQL);
Image1.ImageUrl = rstFighter.Rows[0]["ImagePath"].ToString();
txtDescription.Text = rstFighter.Rows[0]["Description"].ToString();
ViewState["rstFighter"] = rstFighter;
Page.ClientScript.RegisterStartupScript(
this.GetType(),"MyEdit","popimage()", true);
}
And now our save button, to send information back to database is this:
protected void cmdSave_Click(object sender, EventArgs e)
{
// Save comments (and other fields back to database)
DataTable rstFigher = (DataTable)ViewState["rstFighter"];
rstFigher.Rows[0]["Description"] = txtDescription.Text;
SaveData(rstFigher, "Fighters");
LoadGrid(); // refresh grid to show any edits
}
So, the results now look like this when I click on a row image:
Note how the web page behind goes "darker gray" and the pop up is model.
So, I would consider jQuery.UI dialogs.
And I did use two helper routines (after all, we don't write the same code over and over to get get a simple data table, right???).
Those two helper routines were:
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
void SaveData(DataTable rstData,string sTable)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM " + sTable, conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
}
}
}
So, as above shows you have complete control over closing the pop up dialogue, but MUCH more important we can then also with ease update the current page to reflect those changes ( in our example update the description text in our pick list GridView). And with both the grid display and editing on the same page we also require much less code.

Related

how to pass selected row of gridview in popup window into parent page

I have 2 pages in asp.net with c# .
a parent.aspx and popup.aspx.
I passed a querystring(id) into page load of popup.aspx and used function to call row of table base on id and show gridview on popup.aspx.
now I want to select this row, and pass details into text boxes of parent.aspx that is open now.
Everything is ok and row of table is passed into text boxes, but it is into new window popup of parent.aspx page, that I don't want this.
I want pass details into this page(parent.aspx) that now is open.
How can I do that.thanks.
below is my code for pass id to pop-up window
protected void btn_search_id_Click(object sender, ImageClickEventArgs e)
{
string str1 = Encrypt(txt_sh_p.Text);
btn_search_id.Attributes.Add("onclick", "window.open('popup.aspx?sh_p_=" + str1 + "','Report','width=750,height=500,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,left=200,top=50'); return false;");
}
my code for reading id and select row and display row in gridview on page load event of popup.aspx:
protected void Page_Load(object sender, EventArgs e)
{
DAL.Sab_Ashkh sabt_ashkh = new DAL.Sab_Ashkh();
List<DAL.Sab_Ashkh> sabt_ashkh_list;
sabt_ashkh.sh_p = Decrypt(Request.QueryString["sh_p_"]);
sabt_ashkh_list = sabt_ashkhDB.GetShakh_find(sabt_ashkh.sh_p);
grid_ashkh.Visible = true;
grid_ashkh.DataSource = grid_ashkh_list;
grid_ashkh.DataBind();
}
and html code for pass row to parent page:
<Columns>
<asp:HyperLinkField DataTextField="id_shakh" DataNavigateUrlFields="id_shakh" DataNavigateUrlFormatString="parent.aspx?id_shakh={0}"
HeaderText="id" ItemStyle-Width = "150" />
<asp:TemplateField HeaderText="select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width = "150px" DataField = "sh_p" HeaderText ="kod"
>
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
</Columns>
I am just telling you how you can change the variable in Main page in popup page like:
Suppose Parent.aspx have:
<script type="text/javascript">
var items =[];
</script>
and in popup.aspx you can do something like :
window.opener.items.push(yourSelectedRows);
but as another workaround you can also use local storage like:
localStorage.setItem("selectedRecords", JSON.stringify(selectedRows));
suppose selectedRows are your array of object or anything else but as my experience the selectedRecords would be accessible in all HTML pages.
hope this help you.
Hi Aria Thanks for reply. I pass id by query string into popup window and show gridview . and this script for popup win :
<script type="text/javascript">
function SetName() {
if (window.opener != null && !window.opener.closed) {
var txtName = window.opener.document.getElementById("txt_id_mah");
grid = document.getElementById("grid_ashkh");
var cellPivot;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length; i++) {
cellPivot = grid.rows[i].cells[1];
TXT.value = cellPivot;
}
}
}
window.close();
}
</script>
but does not work.

rad window is not opening

i have a radwindow that is being opened by a view column from a rad grid. but the thing is that nothing is happening , the window is not even opening!!!
i want to passe 2 parameters to the RadWindow.
this is the javascript im using:
function ShowEditForm(IdVoiture, IdType, rowIndex) {
var grid = $find("<%= RadGrid1.ClientID %>");
var rowControl = grid.get_masterTableView().get_dataItems()[rowIndex].get_element(); grid.get_masterTableView().selectItem(rowControl, true);
window.radopen("ViewForm.aspx?IdVoiture=" + IdVoiture, "&IdType=" + IdType,"UserListDialog");
return false;
}
and this is my column code from the radGrid:
<telerik:GridTemplateColumn UniqueName="TemplateViewColumn">
<ItemTemplate>
<asp:HyperLink ID="ViewLink" runat="server" Text="View"></asp:HyperLink>
</ItemTemplate>
</telerik:GridTemplateColumn>
this is the code behind:
Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As GridItemEventArgs)
If TypeOf e.Item Is GridDataItem Then
Dim editLink As HyperLink = DirectCast(e.Item.FindControl("ViewLink"), HyperLink)
editLink.Attributes("href") = "#"
editLink.Attributes("onclick") = [String].Format("return ShowEditForm2('{0}','{1}');", e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("DepIDVoit"), 4, e.Item.ItemIndex)
End If
End Sub
i'm not able to locate my error and i tried to do the same as other examples it is still not working please help!!!
****Mark that my code is in an .ascx page contained inside an multipage in a .aspx page , and the javascript is in the .aspx page i dont know if that makes any differencs
i figured out what was missing. my javascript code was correct but my page was missing a RadWindowManager

Add processing image to text in UpdatePanel control

I have an UpdatePanel that displays the text, 'Please wait while the files are created...', when the user clicks the button 'Create Files'. Once the processing is completed, the text is updated to display 'Processing completed'. This works correctly.
What I want to do is add a processing image to the left of the text to show the user that the application is working. I have added the image. When I set the 'Visible' attribute to true, it displays as a spinning circle. What I want to do is display the image only when the text, 'Please wait while the files are created...'.
So initially, I set the image to, Visible-"false". I thought I could just add a line of code to the javascript that displays the text, 'Please wait..' but it is not displaying. Below is my code:
JavaScript:
script type="text/javascript">
$(document).ready(function () {
bindButton();
});
function bindButton() {
$('#<%=btnCreateFiles.ClientID%>').on('click', function () {
$('#<%=lblCaption.ClientID%>').html('Please wait while the label files are being created...');
//I thought I could just add this line and the image would at least display.
//But it does not display. I have also tried setting it to 'visible' and that
//doesn't work either.
// document.getElementById("<%=imgProcessing.ClientID%>").style.display='inline-block';
});
}
</script>
HTML:
<asp:UpdatePanel ID="ProgressUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Image ID="imgProcessing" runat="server" CssClass="floatleft" ImageUrl="~/Images/updateProgress.gif" Visible="false" />
<asp:Label ID="lblCaption" runat="server" CssClass="label" ForeColor="Red" Visible="true"></asp:Label>
<asp:Button ID="btnCreateFiles" runat="server" Text="Create Labels Files" Width="206px" CssClass="label" Height="37px" OnClick="btnCreateFiles_Click" style="float: right"/>
</ContentTemplate>
</asp:UpdatePanel>
This is the Code Behind that is in the Click event:
protected void btnCreateFiles_Click(object sender, EventArgs e)
{
string tstrIssueMonth = string.Empty;
string tstrFolderPath = string.Empty;
try
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(string), "bindButton", "bindButton();", true);
//do processing here
ProgressUpdatePanel.ContentTemplateContainer.Controls.Add(lblCaption);
ProgressUpdatePanel.Update();
lblCaption.ForeColor = Color.Green;
lblCaption.Text = "Processing completed...files have been created.";
}
}
So, I need to be able to show the processing image when the text, 'Please wait...' is shown and when the text 'Processing completed...' is shown the image is not visible.
How do I do that?
Thanks,

Javascript variable problem

I have a variable in javascript:
var activeSearchButton = document.getElementById('<%=btnSearch.ClientID %>');
I want to set it like this:
<asp:TextBox ID="WFTo" runat="server" onchange="activeSearchButton = document.getElementById('<%=btnWFSearch.ClientID %>');"></asp:TextBox>
When I am trying to use the varible in javascript function, it is null. And the source shows:
onchange="activeSearchButton = document.getElementById('<%=btnSearch.ClientID %>');"
I noticed '& lt;' instead of "<". Is this the reason of my problem? Why does this happen? Or maybe there is another reason?
Thank you very much.
Just create a function in <script /> section
function setActiveSearchButton()
{
activeSearchButton = document.getElementById('<%=btnSearch.ClientID %>');
}
and use
<asp:TextBox ID="WFTo" runat="server" onchange="setActiveSearchButton()"></asp:TextBox>
EDIT:
As it turns out, you cannot use <%= .. %> for server side controls. You'll have to resolve to using a regular html input like this
<input type="text" onchange="setActiveSearchButton('<%= btnSearch.ClientID %>')" />
and
function setActiveSearchButton(buttonId)
{
activeSearchButton = document.getElementById(buttonId);
}
or leave the <asp:TextBox /> as it is and on Page_Load do
protected void Page_Load(object sender, EventArgs e)
{
WFTo.Attributes.Add("onchange", "setActiveSearchButton('" + btnSearch.ClientID +"')");
}
You can do this:
onchange='<% = string.Format("activeSearchButton = document.getElementById(\"{0}\");", btnWFSearch.ClientID) %>'
EDIT: As our friend said, we can only do this in a "input" control. For a TextBox the best way is add a parameter in codebehind.

ASP.NET: HtmlGenericControl <DIV> - refresh

I have a DIV element:
<div runat="server" id="path">Nothing here... yet</div>
and JavaScript which changes its content dynamically. After some actions my element looks like this (tested with Firebug, JS is ok):
<div runat="server" id="path">FirstTest - SecondTest - ThirdTest</div>
Then I'd like to save it to text file (<asp:Button runat="server"...):
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
Button1.Click += new EventHandler(this.GreetingBtn_Click);
}
void GreetingBtn_Click(Object sender, EventArgs e)
{
HtmlGenericControl path = (HtmlGenericControl)Page.FindControl("path");
Response.AddHeader("content-disposition", "attachment;filename=download.txt");
Response.ContentType = "text/plain";
Response.Write(path.InnerText);
Response.Flush();
Response.Clear();
Response.End();
}
</script>
It also works OK (SaveDialog popups, user choose location), but... in output file there's only one line "Nothing here... yet". It looks like he doesn't react to changes made by JavaScript!
How can I force him to refresh DIV, so I can always save up-to-date content?
Thanks for any help!
You could update an asp:Hidden with the new value and use that value instead on the post back. The PlaceHolder control is not designed to be a two-way control.
E.g.
function UpdateText()
{
var text = ...;
document.getElementById("<%= path.ClientID %>").innerText = text;
document.getElementById("<%= pathHidden.ClientID %>").value = text;
}

Categories