Force asp.net page postback from server - javascript

I have a page that is created entirely dynamically in the code behind (oh joy).
On pressing a button on this page, more elements are added to the page - which is fine, however, the refreshed page doesn't appear until the next postback. I would do a redirect, but I want to keep the state of any data entered in the existing controls.
So - I need to force a postback from the server code behind code. I imagine that this involves inserting some js code - but beyond that, I've not had any joy at all.
Here is an example to make things clearer:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
A very simple page.
The code behind is simple too:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["data"] = 1;
}
PopulatePage();
}
private void PopulatePage()
{
int data = (int)Session["data"];
for (int n = 0; n < data; ++n)
{
TextBox tb = new TextBox();
tb.ID = n.ToString();
PlaceHolder1.Controls.Add(tb);
Literal lit = new Literal();
lit.Text = "<br/>";
PlaceHolder1.Controls.Add(lit);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int data = (int)Session["data"];
Session["data"] = ++data;
}
}
You click the button and more controls are added. This is way simpler than the page that I am having issues with, but it demonstrates the problems that I am having.

The postback is not needed and is a bit of a hack, you would be better off fixing the problem at the root.
private void PopulatePage()
{
for (int n = 0; n < Counter; n++)
{
CreateSingleControl(n);
}
}
private void CreateSingleControl(int index)
{
TextBox tb = new TextBox();
tb.ID = String.Format("text{0}", index);
PlaceHolder1.Controls.Add(tb);
Literal lit = new Literal();
lit.Text = "<br/>";
PlaceHolder1.Controls.Add(lit);
}
protected override void CreateChildControls()
{
PopulatePage();
base.CreateChildControls();
}
protected void Button1_Click(object sender, EventArgs e) {
CreateSingleControl(Counter);
Counter++;
}
private int Counter
{
get
{
return Counter = (int)(ViewState["data"] ?? 1);
}
set
{
ViewState["data"] = value;
}
}

Use the Request forms list to search unique control ID's
Something like this link below, last post, not sure his code is exactly correct, but you'll get the idea.
Searching for controls in Request.Form / Parsing a NameValueCollection
Give your controls unique IDs' and you can search for them on the postback.
Plus, i use to add other things to the ID to let the postback searching know what type of control it was, like adding txt_firstname, i know that firstname was a txtbox. Use regex to search the returned strings.

Related

asp.net create a dynamic grid with sql data and make it editable

I'm trying to implement a new project. I want to write an SQL table dynamically into e.g. an asp:gridview. And this grid should be editable.
I found some solutions, but they were all static. But it is essential that the table is dynamic, because I want to include different SQL tables in the grid. (The SQL tables sometimes change, columns are removed or new ones are added. Therefore a static solution is not applicable.
Ideally, the editing function should work like in an Excel document. After changing the data, it should be written back to the SQL table with a save button.
Is that even possible? I haven't found a solution to this problem in at least the last 4 hours.
Thank you for your help
Greetings
Update
//HTML Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Personaldaten</h1>
<asp:GridView ID="personal_data" AutoGenerateColumns="true" runat="server"></asp:GridView>
<asp:Button runat="server" ID="button1" text="Save"/>
</div>
</form>
</body>
</html>
//Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Editable_SQL_Table
{
public partial class table : System.Web.UI.Page
{
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
public form1()
{
InitializeComponent();
}
public void form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Server = (localdb)\\MSSQLLocalDB; Database = Personal; Trusted_Connection = True; MultipleActiveResultSets = true");
sda = new SqlDataAdapter(#"SELECT* FROM dbo.MyTable", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
MessageBox.Show("Table updated");
}
}
}
I tried to use the coding from user2980341 but I have a problem with "dataGridView1.DataSource = dt;" I think for "dataGridView1" I should use the id from my Gridview, but I does not work. The debugger says, that he does not recognise "personal_data". Also the function "InitializeComponent();" is undefinded.
Thanks for any further help, I am currently working on the following solution:
//HTML
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="table.aspx.cs" Inherits="Editable_SQL_Table.table" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Personaldaten</h1>
<asp:GridView ID="personal_data" AutoGenerateEditButton="true" AutoGenerateColumns="true" runat="server" OnRowUpdating="personal_data_RowUpdating" OnRowCancelingEdit="personal_data_RowCancelingEdit" OnRowEditing="personal_data_RowEditing"></asp:GridView>
</div>
</form>
</body>
</html>
//Code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Editable_SQL_Table
{
public partial class table : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string table = "dbo.Mitarbeiter";
string query = "SELECT * FROM" + " " + table;
string ConnectionString = "Server = (localdb)\\MSSQLLocalDB; Database = Personal; Trusted_Connection = True; MultipleActiveResultSets = true";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, myConnection))
{
myConnection.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);
personal_data.DataSource = dt;
personal_data.DataBind();
}
}
}
protected void personal_data_RowEditing(object sender, GridViewEditEventArgs e)
{
personal_data.EditIndex = e.NewEditIndex;
}
protected void personal_data_RowUpdating(object sender, GridViewEditEventArgs e)
{
//personal_data.EditIndex = e.NewEditIndex;
}
protected void personal_data_RowCancelingEdit(object sender, GridViewEditEventArgs e)
{
//personal_data.EditIndex = e.NewEditIndex;
}
}
}
Perhaps something like this:
Add DataGridView and a Button element on your form. Then append this code to your elements:
using System.Data.SqlClient;
namespace test
{
public partial class Form1 : Form
{
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection (#"Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;");
sda = new SqlDataAdapter(#"SELECT* FROM dbo.MyTable", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
MessageBox.Show("Table updated");
}
}
}
This program connects to your SQL database and retrives an SQL table from that database. Changes to databse are updated using button1. You cannot however remove or add columns trough this solution.

Getting javascript error for large data in body of mailto function

I want to show data stored in Array-list in body of Mailbox. User can then add mail ids in To: according to his/her convenience and send the mail.
But its throwing JavaScript error when large amount of data is sent to body.
Here is the test code of .aspx page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function mail()
{
var array_store;
array_store = document.getElementById("array_store");
var vs = array_store.value;
window.location.href = "mailto: &body=" + encodeURIComponent(decodeURIComponent(vs));
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button_mail" runat="server" Text="OpenInMailBox" OnClientClick="mail()" />
<input type="hidden" id="array_store" name = "ArrayStore" value = '<%=this.ArrayStore %>' />
</form>
</body>
</html>
Code of .CS page :
public partial class mailto_check : System.Web.UI.Page
{
protected System.Text.StringBuilder ArrayStore = new System.Text.StringBuilder();
string str = "";
protected void Page_Load(object sender, EventArgs e)
{
ArrayList al = new ArrayList();
al.Add("Test1");
al.Add("hello ");
al.Add("Testing");
try
{
for (int y = 0; y < al.Count; y++)
{
str = al[y].ToString();
this.ArrayStore.Append(str+",%0D");
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
for large data I tested it by adding values to array-list.
Please help me with this.
Thanks in advance for positive answers.

Get value from html input text type textbox as string and pass it to C# hashtable being used in aspx

The textbox is defined as html input text type and takes input from the users. This value is needed to pass as key to hashtable defined in aspx.cs file being used in aspx file. But the correct value is not being given and an exception is being thrown. Any help in this regard would be helpful. Thanks
The code is as follows:
<% =Hashtable[document.getElementbyId("Textbox").Value]%>
document.getElementbyId("Textbox").Value is not giving the correct output. If it is replaced by a string value acting as key then it works fine. The only problem is getting the string value from textbox.
First include jquery in head section
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
Try below code to read textbox value :
First read text box value using
var key = $("[id$=Textbox]").val();
and see if value is present in texbox if present use this to read hash value
<% =Hashtable[key]%>
Try this it worked for me :
aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function GetHashtable() {
alert("<% = hashtable[this.test] %>");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtKey" OnTextChanged="txtKey_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
</div>
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</body>
</html>
Code behind :
public partial class _Default : System.Web.UI.Page
{
protected int test;
public Hashtable hashtable = new Hashtable();
static Hashtable sHashtable = new Hashtable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
sHashtable[1] = "One";
sHashtable[2] = "Two";
sHashtable[13] = "Thirteen";
}
}
protected void txtKey_TextChanged(object sender, EventArgs e)
{
test = Convert.ToInt32("0" + txtKey.Text);
hashtable = sHashtable;
Page.ClientScript.RegisterStartupScript(this.GetType(), "GetHashtable", "GetHashtable();", true);
}
}

get the Page's HiddenField Value in UserControl on Page

I want to read the Page(.aspx) Hiddenfield Value in the User Control that is placed on that Page and process some logic.
FOr eg: I have a hidden field x on a Page. The Page has many user controls and I want to access this hidden field (x) in those User Controls where value of x will be set by a Javascript in the Page.
I am trying to find the HiddenControl and read its value from codebehind of usercontrol(.ascx.cs) but always get null.
HiddenField colname = UIUtils.FindControlRecursive(this.Parent.Page, "MainContent_AssignedTo_ColName") as HiddenField;
The ID is same as the hiddenfield on client Side. I tried this.Parent and this.Parent.Parent for the first argument too but no luck.
what am I missing here.
Here is my aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestFindControl._Default" %>
<%# Register Src="ReadHiddenField.ascx" TagName="Assign" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="HiddenField1" runat="server" Value="10">
</asp:HiddenField>
<asp:placeholder ID="Placeholder1" runat="server"><uc1:Assign id="test" runat="server"></uc1:Assign> </asp:placeholder>
</div>
</form>
</body>
</html>
and here is my code behind on control:
protected void Page_Load(object sender, EventArgs e)
{
HiddenField test = (HiddenField)Page.FindControl("HiddenField1");
var j = test.Value;
}
Try:
HiddenField colname = (HiddenField)Page.FindControl("The id of control");
private void GetParentPageHiddenField()
{
System.Web.UI.WebControls.HiddenField ParenthiddenField = null;
Control ctl = this.Parent;
while (true)
{
ParenthiddenField = (System.Web.UI.WebControls.HiddenField)ctl.FindControl("ParentPageHiddenFieldID");
if (ParenthiddenField == null)
{
if (ctl.Parent == null)
{
return;
}
ctl = ctl.Parent;
continue;
}
break;
}
var parentHiddenFieldValue=ParenthiddenField.Value;
}

How to call and pass arguments to a JavaScript method in a page hosted by the .NET WebBrowser control in C#? [duplicate]

This question already has answers here:
Closed 10 years ago.
I want to call a JavaScript function through C#, using a WinForm's WebBrowser control. I've attempted to search however could not find anything which answers my question, only solutions which involved ASP.NET.
Thank you in advance.
Edit:
This is the only question regarding this that I've found that actually has an answer that demonstrates how to call a JavaScript method with parameters, and also shows how to call a .NET function from JavaScript in the WebBrowser control.
I do not think this question should be marked as a duplicate as it adds good value. It's the first hit on a google search for "c# webbrowser call javascript function with parameters".
This is a nice example, that I found here:
http://www.codeproject.com/Tips/127356/Calling-JavaScript-function-from-WinForms-and-vice
HTML/JavaScript
<html>
<head>
<script type="text/javascript">
function ShowMessage(message) {
alert(message);
}
function ShowWinFormsMessage() {
var msg = document.getElementById('txtMessage').value;
return window.external.ShowMessage(msg);
}
</script>
</head>
<body>
<input type="text" id="txtMessage" />
<input type="button" value="Show Message" onclick="ShowWinFormsMessage()" />
</body>
</html>
C#
public partial class frmMain : Form {
public frmMain() {
InitializeComponent();
webBrowser1.ObjectForScripting = new ScriptManager(this);
}
private void btnShowMessage_Click(object sender, EventArgs e) {
object[] o = new object[1];
o[0]=txtMessage.Text;
object result = this.webBrowser1.Document.InvokeScript("ShowMessage", o);
}
private void frmMain_Load(object sender, EventArgs e) {
this.webBrowser1.Navigate(#"E:\Projects\2010\WebBrowserJavaScriptExample\WebBrowserJavaScriptExample\TestPage.htm");
}
[ComVisible(true)]
public class ScriptManager {
frmMain _form;
public ScriptManager(frmMain form) {
_form = form;
}
public void ShowMessage(object obj) {
MessageBox.Show(obj.ToString());
}
}
}

Categories