how to do postback Javascript, jquery - javascript

<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/* post back*/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>
Hi I have this code but I cant do postback for it, im not sure how to?
is it:
<script type="text/javascript">
function CallServer() {
__doPostBack('not sure what goes here','or here');
}
</script>
Then:
<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/CallServer()/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>
My other script:
<script type="text/javascript">
function confirm_delete()
{
if (confirm("Are you sure you want to delete this comment?")==true)
return true;
else
return false;
}
</script>
EDIT:
On the server side i dynamically add a div to my page with content from my database for each content there is a new div will be added, each div is then refrenced with idWallPosting (so i can call my delete function)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Odbc;
using System.IO;
public partial class UserProfileWall : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//btn.Visible = false;
string theUserId = Session["UserID"].ToString();
PopulateWallPosts(theUserId);
}
private void PopulateWallPosts(string userId)
{
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("SELECT idWallPosting, wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN User u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE wp.UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
{
//("SELECT wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN [User] u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
using (OdbcDataReader reader = cmd.ExecuteReader())
{
test1.Controls.Clear();
while (reader.Read())
{
System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
div.Attributes["class"] = "test";
div.ID = String.Format("{0}", reader.GetString(0));
// this line is responsible, problem here and my sqlsntax, im trying to set the SELECT idWallPosting for the div ID
Image img = new Image();
img.ImageUrl = String.Format("{0}", reader.GetString(2));
img.AlternateText = "Test image";
div.Controls.Add(img);
div.Controls.Add(ParseControl(String.Format("&nbsp&nbsp " + "{0}", reader.GetString(1))));
div.Attributes.Add("onclick", "return confirm_delete();");
div.Style["clear"] = "both";
test1.Controls.Add(div);
}
}
}
}
}
//protected void btnDelete_Click(object sender, EventArgs e)
//{
// string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26";
// string[] idFragments = id.Split('_');
// id = idFragments[idFragments.Length - 1];
// //serverside code if confirm was pressed.
// using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
// {
// cn.Open();
// using (OdbcCommand cmd = new OdbcCommand("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
// {
// cmd.ExecuteNonQuery();
// }
// }
// //PopulateWallPosts();
//}
protected void Button1_Click(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString();
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings) VALUES (" + theUserId + ", '" + TextBox1.Text + "')", cn))
{
cmd.ExecuteNonQuery();
}
}
PopulateWallPosts(theUserId);
}
protected void btn_Click(object sender, EventArgs e)
{
string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26";
string[] idFragments = id.Split('_');
id = idFragments[idFragments.Length - 1];
//serverside code if confirm was pressed.
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
{
cmd.ExecuteNonQuery();
}
}
//PopulateWallPosts();
}
}
On my asp.net html side i have:
<script type="text/javascript">
function confirm_delete()
{
if (confirm("Are you sure you want to delete this comment?")==true)
return true;
else
return false;
}
</script>
<p>
<asp:Button ID="btn" OnClientClick="return confirm_delete();" runat="server"
CssClass="Btn" Text="delete" onclick="btn_Click"/>
<asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3"
Height="47px" Width="638px"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Post Message" Width="98px"
onclick="Button1_Click" />
</p>
<p>
</p>
<style type="text/css">
img {border-width:0px; width:100px; height:100px;}
</style>
<div id="test1" runat="server" />
</div>
</asp:Content>
If you notice in my server side code I added this line:
div.Attributes.Add("onclick", "return confirm_delete();")
This works any time I click on my div the confirm_delete is called.
What I was trying to do with my asp.net button was when the div was clicked I could then call the onclick btnDelete_click.

OnClientClick="return confirm_delete();"
That's it...
Edit: __doPostBack works also...
OnClientClick="if(confirm('delete?'))__doPostBack('btn',''); else return false;"

If you really are wanting to manually call __doPostBack(), the first parameter is the .NET generated name for the control. This can be gotten on the server side using Control.ClientID. The second parameter is any extra data that should be passed along in the request. Most of the time I see this field is an empty string.
__doPostBack('ctl100$controlName$id','');
The controlName is the .NET class name of the control I believe, id is the ID you gave the control. To be sure, view the source of the page after it has been rendered in the browser and search for calls to __doPostBack and see how they are formatted.

By a postback in this case do you want to just refresh the page? If so then it would just be:
location.reload();
in your case:
<script type="text/javascript">
function CallServer()
{
location.reload();
}
</script>
Demo (A button click prompts the user to confirm - if they choose Yes, a post back occurs)
See demo here!

One method, not the best for sure:
Add a button into an update panel and set it invisble.
Then call click() method of the button.
Somthing like this:
document.getElementById('button').click();

Related

Edit->Find for WebView2 UI Component (WPF/C#/javascript)

I need to implement "Edit->Find" function for a WebView2 UI Component using WPF/C#/javascript... Below you will find two examples: One that is made for a TextBox UI Control called MainWindow1, and the other that is implemented for a WebView2 UI Control that is called MainWindows2. I'm giving both examples because I need to work the same way for each one. The TextBox example is working, but the WebView2 example is missing some javascript code to finish it and maybe requires some tweeting of the C# calls to WebView2.
First, I implemented a "Find Forward" button for a TextBox that I can click multiple times to find the next string matching the search pattern in the textbox. And Here's my XML and C# for it:
MainWindow1 GUI:
MainWindow1 XML:
<Window x:Class="WpfApp1.MainWindow1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Loaded="Window_Loaded"
Title="MainWindow1" Height="450" Width="800">
<DockPanel LastChildFill="True">
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top" Background="Aqua">
<TextBox Name="TboxFind" Width="80" Text="id"/>
<Button Name="FindForward" Content="FindForward"
Click="FindForward_Click"/>
</StackPanel>
<TextBox Name="textbox1" VerticalScrollBarVisibility="Auto"/>
</DockPanel>
</Window>
MainWindow1 C#:
using System.Text.RegularExpressions;
using System.Windows; using System.Windows.Controls;
namespace WpfApp1 {
public partial class MainWindow1 : Window {
public MainWindow1() {InitializeComponent();}
private void Window_Loaded(object sender, RoutedEventArgs e) {
string text1 = "";
for (int i = 0; i < 10000; i++) {
text1 = text1 + "id" + i.ToString() + "\n";}
textbox1.Text = text1;textbox1.Focus();textbox1.CaretIndex = 0;
}
private void TextBoxGotoLine(TextBox textbox1, int linenum) {
var target_cpos
= textbox1.GetCharacterIndexFromLineIndex(linenum);
var target_char_rect
= textbox1.GetRectFromCharacterIndex(target_cpos);
var first_char_rect = textbox1.GetRectFromCharacterIndex(0);
textbox1.ScrollToVerticalOffset(target_char_rect.Top
- first_char_rect.Top);
}
private void FindForward_Click(object sender, RoutedEventArgs e) {
string pattern = #"(?i)(" + Regex.Escape(TboxFind.Text) + #")";
string text1 = textbox1.Text.Substring(
textbox1.CaretIndex + textbox1.SelectionLength);
var match1 = Regex.Match(text1, pattern);
if (match1.Success) {
textbox1.Focus();
textbox1.Select(textbox1.CaretIndex
+ textbox1.SelectionLength
+ match1.Index, match1.Groups[0].Length);
} //if
} //function
}/*class*/ }/*namespace*/
The problem I'm having is that I also need this same feature for a WebView2 UI Control.
So I install the WebView2 UI Control:
WebView2 Install:
PM > Install-Package Microsoft.Web.WebView2
Add to XML: xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
using Microsoft.Web.WebView2.Core;
And here's my corresponding XML and C# demo code that should work the same as the first example I have given:
MainWindow2 GUI:
MainWindows2 XML:
<Window x:Class="WpfApp1.MainWindow2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wv2
="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Loaded="Window_Loaded"
Title="MainWindow2" Height="450" Width="800" >
<DockPanel LastChildFill="True">
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top" Background="Aqua">
<TextBox Name="SearchStr" Width="80" Text="id"/>
<Button Name="FindForward"
Content="FindForward" Click="FindForward_Click"/>
</StackPanel>
<wv2:WebView2 Name="webview2" CoreWebView2InitializationCompleted
="webview2_CoreWebView2InitializationCompleted" />
</DockPanel>
</Window>
MainWindow2 C#:
using System.Windows; using System.Threading;
using Microsoft.Web.WebView2.Core;
namespace WpfApp1 {
public partial class MainWindow2 : Window {
public MainWindow2() {InitializeComponent(); SearchStr.Focus(); }
private async void Window_Loaded(object sender, RoutedEventArgs e) {
await webview2.EnsureCoreWebView2Async();
}
private void webview2_CoreWebView2InitializationCompleted(
object sender, CoreWebView2InitializationCompletedEventArgs e)
{
string html = "";
for (int i = 0; i < 100; i++) {
string id = "id" + i.ToString();
html = html + "<b>" + id + "</b><br/>";
}
webview2.CoreWebView2.NavigateToString(html);
}
private async Tasks.Task<string> Find(string pattern) {
string js = "";
js = js + "var m1 = document.getElementById(""body"")";
js = js + "/*... ??? what goes here ??? */";
// Find and highlight one at a time, and scroll into view ...
// repeat find from beginning of html body when done ...
// See MainWindow1 example with TextBox for desired behavior here.
return await webview2.ExecuteScriptAsync(js);
}
private void async FindForward_Click(object s, RoutedEventArgs e) {
await Find(SearchStr.Text);
}
}/*class*/ }/*namespace*/
How to use WebBrowser UI Control to do a:
Menu->Edit->Find "SearchStr1"
When I click FindForward Button? I'm thinking it has something to do with executing Javascript on the DOM? each time the button is pressed?

SQL string loop for generated fields on ASP.Net webform

I have the following ASP.Net webform that has a button which can be clicked by the user to generate a bunch of fields (using Javascript) on the form. I also have a bunch of static fields on the form and the values entered on the static fields are transferred to a SQL table. I am having great troubles transferring values that are being entered on the generated fields with a button click. As of now, I'm naming the generated textboxes as txtDimension 2 & so on. I need help to create a SQL string loop that would help me transfer values from both the generated and static fields on the webform.
This is my ASP.Net button code:
<script src="check.js" type="text/javascript"></script>
<div id="divDimensions" class="auto-style9">
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Add More Fields" OnClientClick="return addInput('divDimensions');" CssClass="auto-style10" Height="68px" Width="236px" />
</div>
<p class="auto-style9">
</p>
<p class="auto-style9">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" Width="191px" Height="82px" />
</p>
Javascript code for the ASP.Net button that the user clicks to generate additional fields on the webform:
var counter = 1;
var limit = 1000;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var table = document.getElementById("tableChecksheet");
var row = table.insertRow();
var cell1 = row.insertCell(0);
cell1.className = "auto-style3"
var cell2 = row.insertCell(1);
cell1.innerHTML = "<h2>Dimension Type " + (counter + 1);
cell2.innerHTML = "<br><input id='txtdimensiontype " + (counter + 1) + "' type='text' name='myInputs[]' style='width: 500px;'>";
var row = table.insertRow();
var cell1 = row.insertCell(0);
cell1.className = "auto-style3"
var cell2 = row.insertCell(1);
cell1.innerHTML = "<h2>Dimension " + (counter + 1);
cell2.innerHTML = "<br><input id='txtdimension " + (counter + 1) + "' type='text' name='myInputs[]' style='width: 500px;'>";
counter++;
}
}
C# code behind webform that transfers values entered in the static fields from the webform as of now, I want a SQL string loop for the generated fields:
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.Configuration;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var connectionString = #strConn;
var query = #"INSERT INTO Checksheets (DimensionType, Dimension) VALUES (#sixthword,#seventhword);";
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand(query, connection))
{
command.Parameters.Add(new SqlParameter("#sixthword", txtdimensiontype.Text));
command.Parameters.Add(new SqlParameter("#seventhword", txtdimension.Text));
var Reader = command.ExecuteReader();
}
}
{
Response.Redirect(Request.RawUrl);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
}
}
}
-- for table type to pass to SP
CREATE TYPE [dbo].[NameValuePairTable] AS TABLE( DimensionType [NVARCHAR](MAX) NULL, Dimension [NVARCHAR](MAX) NULL ) GO
-- call SP from C# code and pass it the table type object
CREATE PROCEDURE [dbo].[SaveResultsFromForm]
#NameValuePairAnswers as dbo.NameValuePairTable READONLY
AS
BEGIN
-- this will insert ALL answers from the web form you passed from the c# object
INSERT INTO Checksheets (DimensionType, Dimension)
Select DimensionType, Dimension
FROM #NameValuePairAnswers
END
c#
// now build out the namevalue pair paramater to pass to SP call
SqlParameter TableData = new SqlParameter();
TableData.ParameterName = "#NameValuePairAnswers";
TableData.TypeName = "dbo.NameValuePairTable";
TableData.SqlDbType = SqlDbType.Structured;
// this will be the C# object you populated from your form as a C# datatype DataTable
TableData.Value = FormResultsDataTable;
updated to add more c# code
string SQL = "EXEC dbo.SaveResultsFromForm #NameValuePairAnswers = #NameValuePairAnswers";
SqlCommand InsertDataCommand = new SqlCommand(sSQL);
// now build out the namevalue pair paramater
SqlParameter TableData = new SqlParameter();
TableData.ParameterName = "#NameValuePairAnswers";
TableData.TypeName = "dbo.NameValuePairTable";
TableData.SqlDbType = SqlDbType.Structured;
TableData.Value = FormResultsDataTable;
// now add the tabledata to the list
InsertDataCommand.Parameters.Add(TableData);
// to execute the command to SQL
InsertDataCommand.Execute()

Display the Selected Data With Jumbling

This is my C# code for Jumbling the data.
protected void Button1_Click1(object sender, EventArgs e)
{
ScrambleData("dsafdsfsd");
}
public static string ScrambleData(string data)
{
//string BaseAddress = "http://localhost/";
string BaseAddress = "http://abcd/"; //Calling by Computer Name.
string uri = "ScramblerService/Scrambler?value=" + data;
string CompleteRequestURL = BaseAddress + uri;
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(CompleteRequestURL);
//webrequest.Method = "GET";
webrequest.ContentType = "application/json";
string result;
using (WebResponse response = webrequest.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
return result;
}
}
}
This is my Java Script code for User selected Data.
<script type="text/javascript">
function disp()
{
var txtArea = document.getElementById('MainContent_TextArea1');
var start = txtArea.selectionStart;
var finish = txtArea.selectionEnd;
var sel = txtArea.value.substring(start, finish);
document.getElementById("MainContent_Textarea2").value = sel;
}
</script>
<div>
<asp:TextBox id="TextArea1" runat="server" TextMode="MultiLine" CssClass="form-control" Height="300px"></asp:TextBox>
<INPUT type="button" onclick= "disp()" visible="true" value="Show" class="btn btn-primary"/>
<input id="Textarea2" runat="server" type="text"/>
</div>
Here I am trying to display the user selected data. While displaying the user selected data I need to jumble the words and has to display in Text area2. But I need to call this action through "Show" button Only.
Any Help Please..???
Any Suggestions Please...???
You are referencing an id of "MainContent_Textarea2" but you don't have any element with that ID. You do, however, have one called "Textarea2", have you tried using that?
document.getElementById("Textarea2").value = sel;

Find Button inside a Gridview and click it from codebehind(c#)

I need to click a button that is inside a gridview from the codebehind. I think the best approach will be to create a javascript function in codebehind, something like the second solution i tried below. I will appreciate any help
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Accepted")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
//find button
Button btnEsc = (Button)row.FindControl("btnEsc");
//here I would like to simulate a click on this button, so far no luck
btnEsc.Click(); // this is wrong
}
}
I also try this but it doesn't find the button: I dont know how to find the button inside the gridview
System.Text.StringBuilder sbScript = new System.Text.StringBuilder("");
sbScript.Append("document.getElementById('btnEsc').click();");
ScriptManager.RegisterStartupScript(this, GetType(), "ClientScript", sbScript.ToString(), true);
When you open the lightbox, pass in the Id to a hidden Field. You can then read it out later. Example from ListView here.
protected void lvProjectServices_ItemCreated(object sender, ListViewItemEventArgs e)
{
if (e.Item.DataItem != null)
{
Whatever data = (Whatever)e.Item.DataItem;
PlaceHolder objPlc3 = (PlaceHolder)e.Item.FindControl("phEdit");
LinkButton link3 = new LinkButton();
link3.Text = "<i class=\"table-edit\"></i>";
link3.ID = "lbEditServer" + data.Id.ToString();
link3.CommandName = "Edit";
link3.CommandArgument = data.Id.ToString();
link3.Click += link_Click;
objPlc3.Controls.Add(link3);
}
}
void link_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
int Id = int.Parse(btn.CommandArgument.ToString());
txtProjectServiceId.Value = Id.ToString();
ScriptManager scriptManager = ScriptManager.GetCurrent(Page);
if (!scriptManager.IsClientScriptBlockRegistered("openSvcModal"))
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "openSvcModal", "$('select').select2(); $('#editProjectService').modal();", true);
}
}
Code behind:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btn.Text = "Refreshed";
if (Request.Params["btnPressed"] != null && Request.Params["btnPressed"] == "true")
{
ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", string.Format("$('#{0}').click()", btn.ClientID), true);
}
}
protected void btn_Click(object sender, EventArgs e)
{
btn.Text = "Not Refreshed";
lbl.Text = "Not Refreshed";
System.Threading.Thread.Sleep(1000);
////to refresh the page
Page.Response.Redirect(HttpContext.Current.Request.Url.ToString()+"?btnPressed=true", true);
}
}
Load jquery in aspx page:
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="btn" OnClick="btn_Click" PostBackUrl="/WebForm1.aspx" />
<asp:Label runat="server" ID="lbl"> </asp:Label>
</div>
</form>
</body>
You should really learn jquery, its a great tool. g/l.

How to add new row to repeater without losing information in checkboxes

I have a simple Repeater that contains a checkbox and a Full name per each row.
In addition, I have an "Add Name" button that adds a new full name to the database.
Supposingly user checks a few checkboxes and decides to add another name, I would like to be able to add a new name to the repeater without losing the information in the checkboxes that have been already checked.
I understand some javascript code might do the trick the question is how to approach it?
What do I do?
thanks in advance
p.s.
I'll be glad to hear any advice, not olny regarding js.
Here is quick solution, not very pretty but get the job done. Hope it will give you some new ideas
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RepeaterCheckbox
{
public partial class _Default : System.Web.UI.Page
{
[Serializable]
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
List<Person> personsFromDatabase
{
get { return (List<Person>)ViewState["persons"]; }
set { ViewState["persons"] = value; }
}
//here we will store our person selection state
Dictionary<int,bool> personSelectionState
{
get { return (Dictionary<int, bool>)ViewState["data"]; }
set { ViewState["data"] = value; }
}
protected override void OnLoad(EventArgs e)
{
if (!IsPostBack)
{
#region Test data
personsFromDatabase = new List<Person>{
new Person { Id = 1, Name = "Paul", },
new Person { Id = 2, Name = "Tom", },
};
#endregion
Bind(false);
}
base.OnLoad(e);
}
void Bind(bool isPostback)
{
if (!isPostback)
{
//initialize person selection mapping
personSelectionState = new Dictionary<int, bool>();
foreach (Person person in personsFromDatabase)
personSelectionState.Add(person.Id, false);
}
//map persons to anonymous type that will help us define necessary values
rpPersons.DataSource = personsFromDatabase.Select(x => new
{
Id = x.Id,
Name = x.Name,
//get stored selection state for person
Selected = personSelectionState[x.Id],
});
rpPersons.DataBind();
}
protected void btnAddPerson_Click(object sender, EventArgs e)
{
//update selection states
UpdateSelectionStatuses();
if (!String.IsNullOrEmpty(txbName.Text))
{
//add new person
personsFromDatabase.Add(new Person
{
Id = personsFromDatabase.Count +1,
Name = txbName.Text,
});
//add status mapping for new person so there is no error on postback binding
personSelectionState.Add(personsFromDatabase.Count, false);
//Refresh data on page, to see new person
Bind(true);
}
}
void UpdateSelectionStatuses()
{
//loop through all items
for (int i = 0; i < rpPersons.Items.Count; ++i)
{
RepeaterItem repeaterItem = rpPersons.Items[i];
//find checkbox for item
var checkbox = (CheckBox)repeaterItem.FindControl("chbSelected");
if (checkbox != null)
{
//get our custom attribute
int id = int.Parse(checkbox.Attributes["personId"]);
//update stored checkbox status
personSelectionState[id] = checkbox.Checked;
}
}
}
protected void rpPersons_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var item = e.Item.DataItem;
var checkbox = (CheckBox)e.Item.FindControl("chbSelected");
if (item != null && checkbox != null)
{
//get person id from our helper anonymous type
System.Reflection.PropertyInfo[] anonymousTypeProperties = item.GetType().GetProperties();
int id = (int)anonymousTypeProperties.Where(x => x.Name == "Id").FirstOrDefault().GetValue(item, null);
//set custom attribute on checkbox to map checkbox with person
checkbox.Attributes["personId"] = id.ToString();
}
}
}
}
}
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RepeaterCheckbox._Default" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater runat="server" ID="rpPersons" OnItemDataBound="rpPersons_ItemDataBound" >
<ItemTemplate>
<p>
<asp:CheckBox ID="chbSelected" runat="server" AutoPostBack="false" Checked='<%# DataBinder.Eval(Container.DataItem, "Selected") %>' />
<asp:Label ID="lblName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' />
</p>
</ItemTemplate>
</asp:Repeater>
<div>
<asp:TextBox ID="txbName" runat="server" />
<asp:Button ID="btnAddPerson" runat="server" Text="Add person" OnClick="btnAddPerson_Click" />
</div>
</div>
</form>
</body>
</html>
It depends how do you approach it. Are you using the asp.net repeater in an Ajax update panel?
If is the case you can save check box value at each click event this way when you add a new item the control will be rebinded with the updated values.
If you like to use client side javascript thie post could help you:
How to add rows to a repeater in client side

Categories

Resources