I have a Repeater and when number of data increases the scroll bar is diaplayed.
when i click on any row inside repeater it gets selected and it displays the data correspondingly in next div.
suppose i click on the last record, the data is displayed and row is also highlighted but the scroll goes to its initial position and not last.
Simply put in the following in Page_Load:
this.Page.MaintainScrollPositionOnPostBack = True
Page.MaintainScrollPositionOnPostBack Property
protected void Page_Load(object sender, EventArgs e) { ScrolBar();}
private void ScrolBar()
{
HiddenField PosX = new HiddenField();
HiddenField PosY = new HiddenField();
HtmlControl Form1 = this.Master.FindControl("Form1") as HtmlControl;
PosX.ID = "PosX";
PosY.ID = "PosY";
Form1.Controls.Add(PosX);
Form1.Controls.Add(PosY);
string script;
script = "window.document.getElementById('" + PosX.ClientID + "').value = "
+ "window.document.getElementById('" + test1.ClientID + "').scrollLeft;"
+ "window.document.getElementById('" + PosY.ClientID + "').value = "
+ "window.document.getElementById('" + test1.ClientID + "').scrollTop;";
this.ClientScript.RegisterOnSubmitStatement(this.GetType(), "SavePanelScroll", script);
if (IsPostBack)
{
script = "window.document.getElementById('" + test1.ClientID + "').scrollLeft = "
+ "window.document.getElementById('" + PosX.ClientID + "').value;"
+ "window.document.getElementById('" + test1.ClientID + "').scrollTop = "
+ "window.document.getElementById('" + PosY.ClientID + "').value;";
this.ClientScript.RegisterStartupScript(this.GetType(), "SetPanelScroll", script, true);
}
}
For Repeater or GridView try this:
Put control inside div and add an option OnSorting
<div id="divGridView" runat="server" >
<asp:GridView ID="Grid" runat="server" OnSorting="Grid_OnSorting"
OnDataBound="Grid_DataBound" >
on code file add this method:
protected void Grid_OnSorting(object sender, EventArgs e)
{
divGridView.Page.SetFocus(Grid);
}
You can use below link using jquery
http://www.sergeyakopov.com/2010/11/easily-maintaining-scroll-position-in-gridview-using-jquery
Related
I am trying to append selections from 2 ComboBoxes into a TextBox with a click of a button and I am not sure how to do this. I can do it once with code like this:
private void BTN_APPEND_Click(object sender, EventArgs e)
{
TB_CONNECTORS.Text = CB_PORT_NUMBER.Text + " " + CB_CONNECTOR.Text;
}
And this will result in
Append with the click of a button
but the question is, how can I append to this one more time?
Did you try this :
if(!TB_CONNECTORS.Text == "")
{
TB_CONNECTORS.Text = TB_CONNECTORS.Text + " & " + CB_PORT_NUMBER.Text + " " + CB_CONNECTOR.Text;
}
else
{
TB_CONNECTORS.Text = CB_PORT_NUMBER.Text + " " + CB_CONNECTOR.Text;
}
This will result in the new value achieved from the 2 comboboxes keeping the existing text of the textbox
So while fooling around with webforms, I tried to create a page that outputs a table from a sql server to a html table on Page_Load. I then tried to add a button to a column which would redirect to a page. The only problem is, when I press the button nothing happens at all... I've tried putting breakpoints at the onclick method but they are never reached.
num = ds.Tables[0].Rows.Count;
htmlTable.Append("<tr style='background-color:#bd0000; color: White;'><th>ID</th><th>Job #</th><th>Project</th><th>Completed By</th><th>Date Created</th><th></th></tr>");
if (!object.Equals(ds.Tables[0], null))
{
if (ds.Tables[0].Rows.Count > 0)
{
int MAX_VIEW = (ds.Tables[0].Rows.Count > 15) ? 15 : ds.Tables[0].Rows.Count;
for (int i = 0; i < MAX_VIEW; i++)
{
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Job_Number"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Project_Name"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["CompletedBy"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["DateCreated"] + "</td>");
htmlTable.Append("<td width=\"10%\"><button class=\"astext\" name=\"Btn" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "\" id =\"" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "\" OnClick =\"btnEdit_Click\" runat=\"server\" >Edit</button> | Details</td>");
htmlTable.Append("</tr>");
}
htmlTable.Append("</table>");
DBDataPlaceHolder.Controls.Add(new System.Web.UI.WebControls.Literal { Text = htmlTable.ToString() });
}
else
{
htmlTable.Append("<tr>");
htmlTable.Append("<td align='center' colspan='4'>There is no Record.</td>");
htmlTable.Append("</tr>");
}
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
String id = ((System.Web.UI.WebControls.Button)sender).ID;
Server.Transfer("CcpofDetails.aspx?ID=" + id);
}
}
When I inspect the button in the live form this is what I see
<button class="astext" name="Btn10" id="10" onclick="btnEdit_Click" runat="server">Edit</button>
Your way of generating dynamic controls seems very strange to me. It is not the way web-forms work.
To run an event on a control, it has to be loaded into servers memory first. But you are just filling some html text that is understandable only for the browser, not for asp.net engine.
take a look at this sample
To give you a better idea, create your buttons like this
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
AddControls();
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (ViewState["controsladded"] == null)
AddControls();
}
private void AddControls()
{
TextBox dynamictextbox = new TextBox();
dynamictextbox.Text = "(Enter some text)";
dynamictextbox.ID = "dynamictextbox";
Button dynamicbutton = new Button();
dynamicbutton.Click += new System.EventHandler(dynamicbutton_Click);
dynamicbutton.Text = "Dynamic Button";
Panel1.Controls.Add(dynamictextbox);
Panel1.Controls.Add(new LiteralControl("<BR>"));
Panel1.Controls.Add(new LiteralControl("<BR>"));
Panel1.Controls.Add(dynamicbutton);
ViewState["controlsadded"] = true;
}
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
TextBox tb = new TextBox();
tb = (TextBox) (Panel1.FindControl("dynamictextbox"));
Label1.Text = tb.Text;
}
I believe your problem comes from the fact that ASP.NET doesn't know you created a button. As far as it's concerned, all you did was pump out some text to the page.
As a result, when you post back to the server, it doesn't know it needs to do anything on the server side when you click.
Try creating it as an object (a System.Web.UI.WebControls.Button) and adding that to your page's Controls collection. Be aware that you'll have to do this both on the initial page build and on postback: if the control doesn't exist after postback, events that were hooked up to it don't fire.
Getting it to appear in the middle of your table may require you to do your HTML table creation in some other way, such as building a WebControls Table object and adding that to your Controls collection.
You are not adding corectl the button to the web form. Try this way:
Button btnEdit = New Button();
btn.Edit.Click += btnEdit_Click;
frmMain.Controls.Add(btnSave)
As shown in this question too.
In Visual Studio C# windows form how do I dynamically create a button each time an item is inserted into a listbox ?
When the created button is clicked it has to remove the inserted item from the listbox.
I want to add the button th this:
if (comboBox4.Text != "" && listBox1.Text != "" && comboBox3.Text != "")
{
string ha = listBox1.SelectedItem.ToString();
Clipboard.SetText(comboBox4.Text + "stk " + ha + " i farve " + comboBox3.Text);
listBox2.Items.Add(comboBox4.Text + "stk " + listBox1.SelectedItem.ToString() +
" " + comboBox3.Text);
}
Create a button and add to the form.
Pseudo-code (not the complete solution, only the main login behind it):
public class MyEventArgs: EventArgs
{
public ListBoxValue lbv;
}
...
listBox2.Items.Add(comboBox4.Text + "stk " + listBox1.SelectedItem.ToString() + " " + comboBox3.Text);
Button x = new Button();
x.Text = "whatever";
x.Top = some coordinate;
x.Left = some coordinate;
MyEventArgs me = new MyEventArgs();
me.lbv = inserted lisbox item reference;
x.Click += new ClickHandler(this, me);
myForm.Controls.Add(x);
...
private void ClickHandler(object sender, MyEventArgs e)
{
listbox.Items.Remove(e.lbv);
}
I'm trying to call a function created in code through <asp:Button>'s on click event but its not working...
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
ArrayList myArrayList = ConvertDataSetToArrayList();
Literal objliteral = new Literal();
StringBuilder objSBuilder = new StringBuilder();
// Display each item of ArrayList
foreach (Object row in myArrayList)
{
objSBuilder.Append("<div class='AppItem'>");
objSBuilder.Append("<label class='control-label span3'>" + ((DataRow)row)["PlanName"].ToString() + "</label>");
objSBuilder.Append("<label class='control-label span3'> Plan Description :" + ((DataRow)row)["PlanDesc"].ToString() + "</label>");
objSBuilder.Append("<label class='control-label span3'> Price :" + ((DataRow)row)["PlanCost"].ToString() + "</label>");
objSBuilder.Append("<label class='control-label span3'> Total Visitors :" + ((DataRow)row)["PlanVisitors"].ToString() + "</label>");
objSBuilder.Append("<div class='control-group'><asp:Button Text='AddtoCart' runat='server' id='" + ((DataRow)row)["PlanId"].ToString() + "' class='btn btn-small btn-success' onclick='AddPlanToCart();' /></div>");
//<asp:Button ID="ImageButton1" runat="server" Text="Upload" CssClass="btn btn-small btn-success" onclick="ImageButton1_Click" />
objSBuilder.Append("</div>");
}
objliteral.Text = objSBuilder.ToString();
PlanContent.Controls.Add(objliteral);
}
private void AddPlanToCart()
{
//This does not get called.
}
Click here to see code behind!
The problem here is that you're generating the code to run on the client-side, but including scripts and tags designed to be run through the asp.net processor:
objSBuilder.Append("<div class='control-group'><asp:Button Text='AddtoCart' runat='server' id='" + ((DataRow)row)["PlanId"].ToString() + "' class='btn btn-small btn-success' onclick='AddPlanToCart();' /></div>");
which produces HTML including [slightly reformatted]:
<div class='control-group'>
<asp:Button ... onclick='AddPlanToCart();' />
</div>
instead of the <button> control that you're obviously expecting.
Fixing this to work in the manner its written in would be a significant amount of work. Instead, I'd strongly recommend rewriting it to use an <asp:repeater> control instead.
Your onclick is attempting to call a javascript function AddPlanToCart(). You have a couple of options. Here's 2:
1) Create a javascript that does a postback with a specific query string. Check for the query string in page_load, if it exists then call the function.
2) Create an actual dynamic control. It should be created in Page_init if you want to track it's viewstate, not Page_load. Then Add an event handler for the button.
Button b2 = new Button();
b2.Text = "Add To Cart";
b2.Click += new EventHandler(AddPlanToCart);
When creating the button, you can also bind the click event, to a delegate like the following:
Button btn = new Button();
btn.Text = "Button text";
btn.AutoSize = true;
btn.Location = new Point(y, 0);
btn.Click += delegate(object sender, EventArgs e)
{
solution.Invoke();
};
In this case I am passing an Action<>, as a parameter within the method. When you click on the button, the delegate would be triggered. For instance, this button would be created, and when clicked, a messagebox would show:
Button btn = new Button();
btn.Text = "Button text";
btn.AutoSize = true;
btn.Location = new Point(y, 0);
btn.Click += delegate(object sender, EventArgs e)
{
MessageBox.Show("Clicked!");
};
For your scenario, try something within these lines:
int counter = 0;
// Display each item of ArrayList
foreach (Object row in myArrayList)
{
Control ctrl = new Control();
Label lbl = new Label();
lbl.Text = "Label " + counter.ToString();
Button btn = new Button();
btn.Text = "Button text " + counter.ToString();
btn.Click += delegate(object sender, EventArgs e)
{
Response.Write("<script>alert('Message for button " + counter.ToString() + "');</script>");
};
ctrl.Controls.Add(lbl);
ctrl.Controls.Add(btn);
counter++;
PlanContent.Controls.Add(ctrl);
}
In the following I've taken out irrelevant code. I've created a field called printString. The calculateButton_Click method does a heap of stuff, then I want to send it to a print-friendly page using response.write. However the printString variable doesn't seem to ever stop being "DEFAULT". DEFAULT is all that shows up on my blank page when I click the printButton_Click. Trimmed code below:
public partial class _Default : System.Web.UI.Page
{
private string _printString = "DEFAULT";
protected void Page_Load(object sender, EventArgs e)
{
Response.Buffer = true;
}
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
}
When printButton is clicked it is using the value DEFAULT from when the variable is being set.
private string _printString = "DEFAULT";
Is your problem. You need to maintain the state of printString when the variable is modified. Simply assigning _printString to another value is not persisting the change. You could either write a function to assign _printString to the correct value when printButton is clicked, use ViewState or Session or assign _printString in the printButton click function directly as shown below.
protected void printButton_Click(object sender, EventArgs e)
{
_printString = "Harry Potter";
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
Will result in Harry Potter being wrote to the page.
To use Session:
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["PrintString"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
_printString = (string)Session["PrintString"];
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
ViewState:
ViewState["PrintString"] = "HarryPotter";
Then to retrieve the value you can simply do:
_printString = (string)ViewState["PrintString"];
http://msdn.microsoft.com/en-gb/library/ms972976.aspx
All (instance) variables are disposed at the end of the page's lifecycle since HTTP is stateless(even the controls). You could use a ViewState, HiddenField or Session variable instead.
private string PrintString
{
get
{
if (ViewState["PrintString "] == null || string.IsNullOrEmpty((String)ViewState["PrintString"]))
{
ViewState["PrintString"] = "DEFAULT";
}
return ViewState["PrintString"].ToString();
}
set { ViewState["PrintString"] = value; }
}
There are other options:
Nine Options for Managing Persistent User State in Your ASP.NET Application
The button click event is causing a postback and the _printString value is not being persisted. You need to store it in the calculate method via Session or Viewstate and then set it in the print for example: -
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["bigstring"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
_printString = Session["bigstring"].ToString();
Response.Write(_printString);
Response.Flush();
Response.End();
}