After removing checkbox from checkboxlist, why checkbox isn't adding? - c#

In this program I am dynamically adding CheckBox (by taking input from textbox) in CheckBoxList which itself is created dynamically.
Now when I add checkbox and remove it, everything works fine. When I again try to add checkbox, it is adding in the ArrayList as well as CheckboxList but not showing on the page.
Working on this from past 2 days but couldn't figure out. Please Help!!!
Thank You!
<!--chkboxlist.aspx-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sample</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtchkboxname" runat="server" AutoPostBack="true"></asp:TextBox>
</div>
</form>
</body>
</html>
//chkboxlist.aspx.cs
using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class chkboxlist : System.Web.UI.Page
{
static ArrayList arlst = new ArrayList();
CheckBoxList chklst = new CheckBoxList();
protected void Page_Load(object sender, EventArgs e)
{
if (txtchkboxname.Text != "")
{
arlst.Add(txtchkboxname.Text);
txtchkboxname.Text = "";
}
chklst.DataSource = arlst;
chklst.DataBind();
chklst.AutoPostBack = true;
chklst.SelectedIndexChanged += new EventHandler(this.chklst_OnSelectedIndexChanged);
form1.Controls.Add(chklst);
}
protected void chklst_OnSelectedIndexChanged(object sender, EventArgs e)
{
arlst.RemoveAt(chklst.SelectedIndex);
chklst.DataSource = arlst;
chklst.DataBind();
}
}

Related

Display json data in gridview in .net

I have been created simple shopify app to retrieve product details.
When i access code from gihub.
It run successfully and display product details in text box.
I need to simple change to show the product details in grid view.
Here is dafault.aspx:
existing code;
default.aspx:
<%# Page Language="C#" AutoEventWireup="true" codefile="Default.aspx.cs" Inherits="SampleWebApplication._Default" %>
<!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 id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="APIOutput" TextMode="MultiLine" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
Here is my output screenshot http://s22.postimg.org/xj9zacxa9/untitled.jpg
I need to display product details in gridview,
default.cs:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShopifyAPIAdapterLibrary;
using System.Configuration;
using System.Web.Services;
namespace SampleWebApplication
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ShopifyAuthorizationState state = HttpContext.Current.Session["Shopify.AuthState"] as ShopifyAuthorizationState;
ShopifyAPIClient client
= new ShopifyAPIClient(state);
APIOutput.Text = (string)client.Get("/admin/products.json");
}
}
}
but I just confused with codefile, Can anyone help me get the product details in gridview?
Any help would be highly appreciated.
Thanks in advance.
Try to add reference to json service from visual studio. Then you will have proper classes for your json data, which you can easily parse for yours TextBox.
Using JSON.net you can convert your JSON string to DataTable.
First you need to add JSON.net DLL (http://json.codeplex.com/) in your project. Then add its namespace in your Webpage.
Now DerializeDataTable will return datatable, you need to replace string json variable with your SHOPIfY json result;
public DataTable DerializeDataTable()
{
const string json = #"[{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
+ #"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
+ #"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]";
var table = JsonConvert.DeserializeObject<datatable>(json);
return table;
}
Code to bind GridView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
gvBind(); //Bind gridview
}
}
public void gvBind()
{
var myTable=DerializeDataTable()
gvproducts.DataSource = myTable;
gvproducts.DataBind();
}
Edited:
protected void Page_Load(object sender, EventArgs e)
{
ShopifyAuthorizationState state = HttpContext.Current.Session["Shopify.AuthState"] as ShopifyAuthorizationState;
ShopifyAPIClient client
= new ShopifyAPIClient(state);
var myJsonString = (string)client.Get("/admin/products.json");
var table = JsonConvert.DeserializeObject<datatable>(myJsonString );
gvproducts.DataSource = table ;
gvproducts.DataBind();
}

How to add ASP.net and HTML Controls to the page at runtime?

I have an ASP.net WebForm. The markup is like:
<div>
<input type="text" id="input" runat="server" value=" " />
<asp:Button Text="send" OnClick="btnsend_Click" ID="btnsend" runat="server" />
</div>
This HTML is generated at runtime . The events are defined in the code behind file.
I need to add these controls at runtime. I tried to use the Literal-Control but the controls are working just like HTML Controls and not like ASP.net Controls.
EDIT:
Note: The Project type should be Website, not a web Application. Web application won't support on demand compilation where website yes, it is.
If I understood currectly, you want to take the Markup from User which contains even asp.net controls and scriplets too.
if this is the case, Follow below steps:
Create a dummy .ascx control file, like DynamicMarkup.ascx with empty content
Add this user control to the page (xxxx.aspx) where you want to show this control statically so it registered to the page
<%# Register src="~/DynamicMarkup.ascx"
tagname="DynamicMarkup" tagprefix="MyASP" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server"
ID="DynamicMarkupContainer" ></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Write user input markup (may be get from database based on your criteria) to the DynamicMarkup.ascx file in page OnInit of the page (xxxx.aspx) And the create object of this DynamicMarkup
DynamicMarkup dynamicMarkup = LoadControl("~/DynamicMarkup.ascx") as
DynamicMarkup;
DynamicMarkupContainer.Controls.Add(ucSimpleControl);
I have not tested this approach, Just give a thought, With this you may get some session overwriting issue which you need handle.
Hope this will help!!
OLD:
is this the one that you are expecting? TextBox, and Button controls are available in System.Web.UI.WebControls namespace.
void Page_Load(Object sender, EventArgs e)
{
TextBox input = new TextBox();
input.Id ="input";
this.PlaceHolder.Controls.Add(input);
Button btnSend=new Button();
btnSend.Id ="btnSend";
btnSend.Text="Send";
btnSend.Click += new EventHandler(btnSend_Click);
this.PlaceHolder.Controls.Add(btnSend);
}
void btnSend_Click(object sender, EventArgs e)
{
// throw new NotImplementedException();
}
<%# 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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder ID="phHolder" runat="server"></asp:PlaceHolder>
</form>
</body>
</html>
code behind :
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Init()
{
GenerateContorls();
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void GenerateContorls()
{
TextBox newTxt = new TextBox() { ID = "txtsend" };
Button newBtn = new Button() { Text = "Send", ID = "btnsend" };
newBtn.Click += btnsend_Click;
phHolder.Controls.Add(newTxt);
phHolder.Controls.Add(newBtn);
}
protected void btnsend_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)this.FindControl("txtsend");
//your code
}
}
hope it helps

strange behaviour of asplistbox

first I checked every word here :
Click questions/6621510
My problem description:
I have the next design :
<asp:UpdatePanel ID="updPnltmpTermCats" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<div class="alt">
<div class="msgnoteborder">
<div class="panelistbox">
<asp:ListBox ID="lsttmpTermCats" runat="server" DataValueField="ProposalTermCatID" DataTextField="TermCatName"
Rows="10" SelectionMode="Single" AutoPostBack="true" OnSelectedIndexChanged="lsttmpTermCats_SelectedIndexChanged" />
</div>
<div class="panelistbox">
<asp:ListBox ID="lstTermSubCat" runat="server" DataValueField="ProposalTermSubCatID" DataTextField="TermVirtualName"
Rows="10" SelectionMode="Single" OnDataBinding="lstTermSubCat_DataBinding" OnDataBound="lstTermSubCat_DataBound" ViewStateMode="Enabled" />
<div class="layoutbuttons">
<asp:ImageButton ID="TermSubCatUpBtn" runat="server" ImageUrl="~/Data/SiteImages/up.gif"
CommandName="up"
CommandArgument="TermSubCat"
SkinID="pageLayoutMoveUp" CssClass="btnup" />
<asp:ImageButton ID="TermSubCatDownBtn" runat="server" ImageUrl="~/Data/SiteImages/dn.gif"
CommandName="down"
CommandArgument="TermSubCat"
SkinID="pageLayoutMoveDown"
CssClass="btndown" />
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
With code behind :
protected void lstTermSubCat_DataBound(object sender, EventArgs e)
{
int indx = -1;
indx = lstTermSubCat.SelectedIndex;
string txt = string.Empty;
txt = lstTermSubCat.Items[indx].Text;
lstTermSubCat.Items[indx].Text = Regex.Replace((txt).ToString(), #"<[^>]*>", String.Empty).Replace("\r\n", String.Empty).Trim();
}
protected void lstTermSubCat_DataBinding(object sender, EventArgs e)
{
// ListItem item = lstTermSubCat.Items. .Item;
int indx = -1;
indx = lstTermSubCat.SelectedIndex;
string txt = string.Empty;
txt = lstTermSubCat.Items[indx].Text;
lstTermSubCat.Items[indx].Text = Regex.Replace((txt).ToString(), #"<[^>]*>", String.Empty).Replace("\r\n", String.Empty).Trim();
}
If i put OnSelectedIndexChanged in the second listbox it will works but other events are not firing !
ok,
it is rely strange!
i made new page
simple one :
the design is :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="testlist.aspx.cs" Inherits="UHSRFP.Features.UI.Admin.UHSRFP.Proposal.testlist" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="updPnltmpTermCats" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:ListBox ID="lsttmpTermCats" runat="server"
DataValueField="ProposalTermCatID" DataTextField="TermCatName"
Rows="10" SelectionMode="Single" AutoPostBack="true"
OnSelectedIndexChanged="lsttmpTermCats_SelectedIndexChanged"
OnDataBinding="lsttmpTermCats_DataBinding"
OnDataBound="lsttmpTermCats_DataBound" />
<asp:ListBox ID="lstTermSubCat" runat="server"
DataValueField="ProposalTermSubCatID" DataTextField="TermVirtualName"
Rows="10" SelectionMode="Single" AutoPostBack="true"
OnSelectedIndexChanged="lsttmpTermCats_SelectedIndexChanged"
OnDataBinding="lstTermSubCat_DataBinding"
OnDataBound="lstTermSubCat_DataBound"
/>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
and the code behind is :
using System;
using System.IO;
using System.Web;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Globalization;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using UHSRFP.Business;
using UHSRFP.Features.UI.Helper;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using mojoPortal.Web;
using mojoPortal.Web.AdminUI;
using mojoPortal.Web.Editor;
using mojoPortal.Web.UI;
using Resources;
namespace UHSRFP.Features.UI.Admin.UHSRFP.Proposal
{
public partial class testlist : System.Web.UI.Page
{
private int proposalID = 11;
private int siteid = 1;
int termCatID = -1;
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();
}
private void PopulateControls()
{
if ((this.proposalID > 0) & (!Page.IsPostBack))
{
Bind_tmpTermCatList();
//Bind_TermSubCatList();
}
}
private void Bind_tmpTermCatList()
{
lsttmpTermCats.Items.Clear();
ArrayList proposalTermCategories = ProposalTermCategory.GetArrayProposalTermCats(this.siteid, this.proposalID);
foreach (ProposalTermCategory proposalTermCategory in proposalTermCategories)
{
ListItem listItem = new ListItem(proposalTermCategory.TermCat.Coalesce(Resource.ContentNoTitle), proposalTermCategory.ProposalTermCatID.ToInvariantString());
lsttmpTermCats.Items.Add(listItem);
}
if (this.lsttmpTermCats.Items.Count > 0)
this.lsttmpTermCats.SelectedIndex = 0;
this.termCatID = int.Parse(lsttmpTermCats.SelectedValue);
ListItem item = lsttmpTermCats.Items.FindByValue(this.termCatID.ToInvariantString());
if (item != null)
{
lsttmpTermCats.ClearSelection();
item.Selected = true;
}
Bind_TermSubCatList();
}
private void Bind_TermSubCatList()
{
lstTermSubCat.Items.Clear();
ArrayList proposalTermSubCategories = ProposalTermSubCategory.GetArrayProposalTermSubCats(this.siteid, this.termCatID);
foreach (ProposalTermSubCategory proposalTermSubCategory in proposalTermSubCategories)
{
ListItem listItem = new ListItem(proposalTermSubCategory.TermSubCatDescr.Coalesce(Resource.ContentNoTitle), proposalTermSubCategory.ProposalTermSubCatID.ToInvariantString());
lstTermSubCat.Items.Add(listItem);
}
}
protected void lstTermSubCat_DataBound(object sender, EventArgs e)
{
// ListItem item = lstTermSubCat.Items. .Item;
int indx = -1;
indx = lstTermSubCat.SelectedIndex;
string txt = string.Empty;
txt = lstTermSubCat.Items[indx].Text;
lstTermSubCat.Items[indx].Text = Regex.Replace((txt).ToString(), #"<[^>]*>", String.Empty).Replace("\r\n", String.Empty).Trim();
}
protected void lstTermSubCat_DataBinding(object sender, EventArgs e)
{
// ListItem item = lstTermSubCat.Items. .Item;
int indx = -1;
indx = lstTermSubCat.SelectedIndex;
string txt = string.Empty;
txt = lstTermSubCat.Items[indx].Text;
lstTermSubCat.Items[indx].Text = Regex.Replace((txt).ToString(), #"<[^>]*>", String.Empty).Replace("\r\n", String.Empty).Trim();
}
protected void lsttmpTermCats_SelectedIndexChanged(object sender, EventArgs e)
{
this.termCatID = int.Parse(lsttmpTermCats.SelectedValue);
Bind_TermSubCatList();
}
protected void lsttmpTermCats_DataBinding(object sender, EventArgs e)
{
this.termCatID = int.Parse(lsttmpTermCats.SelectedValue);
//Bind_TermSubCatList();
}
protected void lsttmpTermCats_DataBound(object sender, EventArgs e)
{
this.termCatID = int.Parse(lsttmpTermCats.SelectedValue);
}
}
}
and still not working
the problem is that ONLY the events OnDataBinding and OnDataBound are not firing while on index change still working well !!
is there any tip here please ?
any help here will be as gift cause i spent long time trying every thing without results !!!
thanks
Remember if your controls don't have the bound data-source when the page is fully rendered they won't fire neither DataBinding nor DataBound events for you.
So you must bind the data-source either on their control properties (.aspx file) or on your Page_load event before the control fire the DataBiniding or DataBound event.
therefore you need to use DataBind() method after you set the data to your controls.
private void Bind_tmpTermCatList()
{
//your datasource code here
lsttmpTermCats.DataBind(); //bind your control here
Bind_TermSubCatList();
}
and in your sub list you will have something like this:
private void Bind_TermSubCatList()
{
// your datasource code here...
lstTermSubCat.DataBind(); //bind your sub control here
}
now you will see two events lsttmpTermCats_DataBinding and lsttmpTermCats_DataBound will fire afterwards.
Cheers

Prevent duplication in asp:table on refresh using AJAX timer

I've created a very simple bit of code in C# to display data in an asp:Table. On the initial page load all looks great. I've used an AJAX timer to refresh every 15 seconds to keep the data up to date. The problem is after it refreshes the table shows all the data duplicated. I've tried debugging and again all looks good until the AJAX refresh and then it seems to jump all over the place in the C# code rather than following the expected sequence.
Hopefully I've not approached this in completely the wrong way but if I have please tell me! Is there a way to prevent/fix this duplication?
I've replicated the problem code here in a very simple form. Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="testASPTables._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Table ID="Table1" runat="server">
</asp:Table>
<asp:Timer ID="Timer1" runat="server" Interval="15000" OnTick="Timer1_Tick">
</asp:Timer>
</div>
</form>
</body>
</html>
...and the codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace testASPTables
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TableRow[] tRows = new TableRow[5];
TableCell[] tCells = new TableCell[5];
for (int i = 0; i < 5; i++)
{
tRows[i] = new TableRow();
Table1.Rows.Add(tRows[i]);
tCells[i] = new TableCell();
tRows[i].Cells.Add(tCells[i]);
tCells[i].Text = "Cell Number: " + i.ToString();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Page_Load(sender, e);
}
}
}
You're calling Page_Load twice. Page_Load runs on postback, then you call it again from Timer1_Click.
You need to always be concious of whether the page is in a postback or not and how Page_Load works.
Here's what I'd do.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
LoadTableData();
}
}
protected void LoadTableData()
{
Table1.Rows.Clear(); //I added this
TableRow[] tRows = new TableRow[5];
TableCell[] tCells = new TableCell[5];
for (int i = 0; i < 5; i++)
{
tRows[i] = new TableRow();
Table1.Rows.Add(tRows[i]);
tCells[i] = new TableCell();
tRows[i].Cells.Add(tCells[i]);
tCells[i].Text = "Cell Number: " + i.ToString();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
LoadTableData();
}
Oh, and in addition to that, you'd need to clear the existing table rows.
By the way, this is very inefficient. You're reloading the entire table every 15 seconds. Multiple that by a few clients and you're practically performing a DoS attack on yourself. Consider using SignalR to push new changes to the clients as rows are added to the underlying data.

Dynamically created textbox values losses when i click the button

I have created a TextBox dynamically, and i am getting the value of the textbox when i click the button. But the value entered in the dynamic textbox gets empty when i click the button.
Below is my ASPX Code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Reports.WebForm1" %>
<!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>
</div>
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack = "true">
<asp:ListItem>Text</asp:ListItem>
<asp:ListItem>Check</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="GetTextBoxValue" />
</form>
</body>
</html>
CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Reports
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox TB = new TextBox();
TB.ID = "abc";
form1.Controls.Add(TB);
Response.Write(Request.Form["abc"]);
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
createcontrol();
}
protected void createcontrol()
{
if (DropDownList1.SelectedValue.ToLower().Trim() == "text")
{
TextBox TB = new TextBox();
TB.ID = "abc";
form1.Controls.Add(TB);
}
}
}
}
When you use dynamic controls in .NET and want their values to be accessible after postback you need to create them within the Page_Init method of the page. In essence its not working because ViewState has already been set by the time you created the controls. See this guide for detailed info on this topic https://web.archive.org/web/20211020131055/https://www.4guysfromrolla.com/articles/081402-1.aspx . To fix the problem elevate your Textbox instantiation code to the Page_Init method and all should be well.

Categories

Resources