I have a grid with two columns first column with check box and second column with text box. I have a add and save button down the grid.Can you please tell how to obtain if i click add button i need to append one more row to the grid with empty text box and check box so that i can type and click save
need to do possibly without java script
If I am getting you correctly you want something like below
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>
<!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:GridView ID="grdDemo" runat="server" AutoGenerateColumns="False" EnableModelValidation="True">
<Columns>
<asp:TemplateField HeaderText="CheckBox">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("IsCheckBox") %>' Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TextBox">
<ItemTemplate>
<asp:TextBox ID="Label1" runat="server" Text='<%# Bind("IsTextBox") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" />
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Caching;
public partial class Default5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grdDemo.DataSource = new Demo().GetData();
grdDemo.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var list = new Demo().GetData();
list.Add(new Demo() {IsCheckBox = false, IsTextBox = ""});
Cache["list"] = list;
grdDemo.DataSource = list;
grdDemo.DataBind();
}
}
public class Demo
{
public bool IsCheckBox { get; set; }
public string IsTextBox { get; set; }
public List<Demo> GetData()
{
if (HttpContext.Current.Cache["list"] == null)
{
List<Demo> list = new List<Demo>()
{
new Demo(){IsCheckBox=true,IsTextBox = "text1"},
new Demo(){IsCheckBox=false,IsTextBox = "text2"},
};
return list;
}
return (List<Demo>)HttpContext.Current.Cache["list"];
}
}
Related
I am having trouble retrieving a TextBox control's ClientID value from a ListView control.
I thought this syntax would return me the ClientID fine(very strange):
((TextBox)e.Item.FindControl("amount")).ClientID;
but it keeps throwing this exception:
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
Any help is greatly appreciated.
Below is my code:
aspx:
<asp:ListView ID="categories" runat="server"
ClientIDRowSuffix="ID"
ItemPlaceholderID="categoryItem"
DataKeyNames="ID" onitemdatabound="categories_ItemDataBound">
<ItemTemplate>
<div class="category">
<asp:TextBox ID="amount" runat="server" />
</div>
</ItemTemplate>
</asp:ListView>
codebehind:
public string AmountTextBoxClientID { get; set; }
protected string GetAmountTextBoxClientID()
{
return this.AmountTextBoxClientID;
}
protected void categories_ItemDataBound(object sender, ListViewItemEventArgs e)
{
switch (e.Item.ItemType)
{
case ListViewItemType.DataItem:
TextBox amountTextBox = (TextBox)e.Item.FindControl("amount");//this line excutes without any error
amountTextBox.Text = categoryAmount.ToString("C");
amountTextBox.Attributes.Add("readonly", "readonly");
this.AmountTextBoxClientID = amountTextBox.ClientID; //this line keeps throwing the OutOfRange exception
break;
}
}
Im afraid I cant pinpoint your problem but i drew up a page based on what you've given and pasted it below. It does NOT error.
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public string AmountTextBoxClientID { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("column1");
DataRow dr = dt.NewRow();
dr[0] = "some data";
dt.Rows.Add(dr);
ListView1.DataSource = dt;
ListView1.DataBind();
}
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
TextBox tbAmount = (TextBox)e.Item.FindControl("amount");
this.AmountTextBoxClientID = tbAmount.ClientID;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="ListView1" runat="server" onitemdatabound="ListView1_ItemDataBound">
<ItemTemplate>
<asp:TextBox ID="amount" runat="server" />
</ItemTemplate>
</asp:ListView>
</div>
</form>
</body>
</html>
I want to update the text property of my textbox control in Asp.Net from within loop.I have tried using Ajax updatepanel with the timer control but unable to update the text property.I have been searching this since last week but unable to find any answer any help would be higly appreciated
Following is the detail:
This is my button click event in this code you can see I am updating the
TxtContent.Text
within a loop the text is being returned by a user defined function called
ReturnBodyText()
afterwards I am assigning the text to the viewstate so that at the timer tick event I can recall the text and update the textbox text property and then at the timer tick event assigning the viewstate values to the textbox.
protected void Button4_Click(object sender, EventArgs e)
{
ArrayList FilePath = (ArrayList)ViewState["ArrayList"];
int i = 0;
int b = 1;
foreach(string[] sr in FilePath)
{
string Month = sr[i];
string datewithzero;
datewithzero = String.Format("{0:00}", b);
string[] FilesArray = (string[])listfiles(Month, datewithzero).ToArray(typeof(string));
foreach (string FileNameWithExtension in FilesArray)
{
ListBox4.Items.Add(FileNameWithExtension);
TxtContent.Text = ReturnBodyText(Month, datewithzero, FileNameWithExtension);
ViewState["Content"] = TxtContent.Text;
Timer1.Enabled = true;
Timer1_Tick(ViewState["Content"], e);
}
i = i + 1;
b = b + 1;
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
TxtContent.Text =(string) ViewState["Content"];
TxtContent.DataBind();
}
I Hope the above description will help you guys in understanding my problem
The complete aspx file and the code behind is as follows:
Aspx Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:ListBox ID="ListBox1" runat="server" Height="509px" Width="59px">
</asp:ListBox>
<asp:Button ID="Button2" runat="server" Height="26px" onclick="Button2_Click"
Text="To be pressed first" Width="130px" />
<asp:Button ID="Button3" runat="server" onclick="Button3_Click"
Text="To be pressed 2nd" Width="131px" Height="26px" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="1000"
ontick="Timer1_Tick" Enabled="False">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="TxtContent" runat="server" Height="508px" AutoPostBack="True"
TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="Button5" runat="server" Height="26px" onclick="Button4_Click"
Text="To be pressed Third" Width="122px" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
- Codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Collections;
public partial class _Default : ftp
{
protected void Button2_Click(object sender, EventArgs e)
{
string[] array = (string[])listfiles().ToArray(typeof(string));
ViewState["FolderName"] = array;
foreach (string FileName in array)
{
ListBox1.Items.Add(FileName);
}
}
protected void Button3_Click(object sender, EventArgs e)
{
string[] arraylistbox2 = (string[])ViewState["FolderName"];
string[] arrays = new string[12];
ArrayList ListPath = new ArrayList();
int dateFolder;
foreach (string FileName in arraylistbox2)
{
dateFolder = Convert.ToInt16(FileName);
dateFolder = dateFolder - 1;
ListPath.Add((string[])(listfiles(FileName).ToArray(typeof(string))));
}
ViewState["ArrayList"] = ListPath;
}
protected void Button4_Click(object sender, EventArgs e)
{
ArrayList FilePath = (ArrayList)ViewState["ArrayList"];
int i = 0;
int b = 1;
foreach(string[] sr in FilePath)
{
string Month = sr[i];
string datewithzero;
datewithzero = String.Format("{0:00}", b);
string[] FilesArray = (string[])listfiles(Month, datewithzero).ToArray(typeof(string));
foreach (string FileNameWithExtension in FilesArray)
{
TxtContent.Text = ReturnBodyText(Month, datewithzero, FileNameWithExtension);
ViewState["Content"] = TxtContent.Text;
Timer1.Enabled = true;
Timer1_Tick(ViewState["Content"], e);
}
i = i + 1;
b = b + 1;
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
TxtContent.Text =(string) ViewState["Content"];
TxtContent.DataBind();
}
Sadly, your code did not help me much. However, I wrote this which I believe does what you want -partially-. It seems to me nothing more can be done though. Here is the code:
.aspx file:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" ID="Timer1" Interval="1000" Enabled="true"
ontick="Timer1_Tick" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
aspx.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected static string keeper;
protected static bool inUse = false;
protected void Page_Load(object sender, EventArgs e) {}
protected void Button1_Click(object sender, EventArgs e)
{
Thread worker = new Thread(new ThreadStart(workerFunction));
worker.Start();
return;
}
protected void workerFunction()
{
inUse = true;
for (int i = 0; i < 3; i++)
{
TextBox1.Text += "foo";
keeper = TextBox1.Text;
Thread.Sleep(1000);
}
inUse = false;
keeper = "";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
if (inUse)
{
TextBox1.Text = Convert.ToString(keeper);
}
}
}
}
I'd like to bind a List of Dictionary to a GridView.
var liste = new List<Dictionary<string, string>>();
var dictionary = new Dictionary<string,string>();
dictionary["Id"] = "111";
dictionary["Description"] = "text to show";
dictionary["OtherInfo"] = "other text";
liste.Add(dictionary);
gvClients.DataSource = liste;
gvClients.DataBind();
The code in the aspx :
<asp:GridView ID="gvClients" runat="server" AutoGenerateColumns="true" GridLines="None"
AllowPaging="True" CssClass="gridview" AlternatingRowStyle-CssClass="alt" Width="80%">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
<asp:TemplateField HeaderText="PropertyName">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PropertyName">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("OtherInfo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
How can I bind the GridView to that Object (or a System.Collections.HashTable).
edit
The geek's solution for Dictionary work but not for HashTable, is there a solution ?
var liste = new List<System.Collections.Hashtable>();
var table = new System.Collections.Hashtable();
table["Denomination"] = "a";
table["Denomination2"] = "an";
liste.Add(table);
var result = liste.Select(map => new
{
IdClient = map["Denomination"],
Denomination = map["Denomination2"]
}).ToList();
gvClients.DataSource = result;
gvClients.DataBind();
I've this error :
The data source for GridView with id 'gvClients' did not have any properties or attributes from which to generate columns.
When I modify the mapping like this :
var result = liste.Select(map => new
{
IdClient = map["Denomination"],
Denomination = map["Denomination2"],
Test = "test"
}).ToList();
It will show only the Test property.
Thanks
Check out the following code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvClients" runat="server" AutoGenerateColumns="false" GridLines="None"
CssClass="gridview" AlternatingRowStyle-CssClass="alt" Width="80%">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
<asp:BoundField DataField="Key" />
<asp:BoundField DataField="Value" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var liste = new List<Dictionary<string, string>>();
var dictionary = new Dictionary<string, string>();
dictionary["PropertyName"] = "text to show";
var dictionary2 = new Dictionary<string, string>();
dictionary2["PropertyName"] = "text to show1";
liste.Add(dictionary2);
liste.Add(dictionary);
var result = liste.SelectMany(x => x);
gvClients.DataSource = result;
gvClients.DataBind();
}
}
}
Edit
I have edited the code as per your requirements.Please try this code and let me know if you experience any problems .
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!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:GridView ID="gvClients" runat="server" AutoGenerateColumns="true" GridLines="None"
CssClass="gridview" AlternatingRowStyle-CssClass="alt" Width="80%">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OtherInfo">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("OtherInfo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public class Client
{
public string ID { get; set; }
public string Description { get; set; }
public string OtherInfo { get; set; }
}
public partial class Default3 : System.Web.UI.Page
{
List<Client> list=new List<Client>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var liste = new List<Dictionary<string, string>>();
var dictionary = new Dictionary<string, string>();
dictionary["ID"] = "111";
dictionary["Description"] = "XYZ";
dictionary["OtherInfo"] = "Addd";
liste.Add(dictionary);
var result = liste.Select(map => new Client
{
ID = map["ID"],
Description = map["Description"],
OtherInfo = map["OtherInfo"]
}).ToList();
gvClients.DataSource = result;
gvClients.DataBind();
}
}
}
EDITII
If you want to use Hashtable then do the following
Create a new class named Client (what ever you want)
public class Client
{
public string IdClient { get; set; }
public string Denomination { get; set; }
}
and then query the list as follows
var liste = new List<Hashtable>();
var table = new Hashtable();
table["Denomination"] = "a";
table["Denomination2"] = "an";
liste.Add(table);
var result = liste.Select(map => new Client()
{
IdClient = map["Denomination"].ToString(),
Denomination = map["Denomination2"].ToString()
});
gvClients.DataSource = result;
gvClients.DataBind();
i am calling two server side function with the help of page method but nothing happen.
here i am giving my code. so please tell me what mistake i made,
my aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.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">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div>
Test
<br />
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="btnSetvwState" runat="server" Text="Set Session Val" OnClientClick="SetSessionVal;return false;" />
<asp:Button ID="btnGetVwState" runat="server" Text="Get Session Val" OnClientClick="GetSessionVal;return false;"/>
<script language="javascript">
function preview() {
alert($get('TextBox1').value);
PageMethods.GetMessage("Hi", "Joy", onSuccess)
return false;
}
function onSuccess(res) {
alert(res);
}
function GetSessionVal() {
PageMethods.GetViewState(onSuccess)
return false;
}
function SetSessionVal() {
alert("pp");
PageMethods.SetViewState("Hi", "Tridip", onSuccess)
return false;
}
</script>
</form>
</body>
</html>
my server side code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string GetMessage(string pr1,string pr2)
{
return pr1 + " " + pr2;
}
[System.Web.Services.WebMethod(EnableSession=true)]
public static void SetViewState()
{
HttpContext.Current.Session["data"] = "Hellp";
}
[System.Web.Services.WebMethod(EnableSession = true)]
public static string GetViewState()
{
return (String) HttpContext.Current.Session["data"] ;
}
}
}
please help me to catch the mistake. thanks
missing () here (SetSessionVal, GetSessionVal):
<asp:Button ID="btnSetvwState"
runat="server" Text="Set Session Val"
OnClientClick="SetSessionVal();return false;" />
<asp:Button ID="btnGetVwState"
runat="server" Text="Get Session Val"
OnClientClick="GetSessionVal();return false;"/>
TemplateField tf1 = new TemplateField();
tf1.ItemTemplate = ???
How to initialize this property?
If I need to this programmatically then what to do?
TemplateField tf1 = new TemplateField();
tf1.ItemTemplate = Page.LoadTemplate("ItemTemplate.ascx");
You would usually do this sort of thing in the markup:
<TemplateField ...>
<ItemTemplate>
<asp:TextBox .../>
</ItemTemplate>
</TemplateField>
or do the same thing using the designer.
Example follows. The commented-out markup produces the same thing as the codebehind does:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
SelectCommand="SELECT Person.Contact.FirstName, Person.Contact.LastName
FROM Person.Contact
INNER JOIN HumanResources.Employee ON Person.Contact.ContactID = HumanResources.Employee.ContactID
WHERE (Person.Contact.LastName LIKE N'A%')
ORDER BY Person.Contact.LastName, Person.Contact.FirstName">
</asp:SqlDataSource>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<%-- <ItemTemplate>
<asp:Label runat="server" ID="lblLast">Name: </asp:Label>
<asp:Label runat="server" ID="lblName" Text='<%# DataBinder.Eval(Container.DataItem, "LastName")+", "+DataBinder.Eval(Container.DataItem, "FirstName") %>' />
</ItemTemplate>--%>
<SeparatorTemplate>
<hr />
</SeparatorTemplate>
</asp:Repeater>
</form>
</body>
</html>
Codebehind:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Repeater1.ItemTemplate = new TheItemTemplate();
}
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
}
public class TheItemTemplate : ITemplate
{
#region Implementation of ITemplate
public void InstantiateIn(Control container)
{
var lblLast = new Label {ID = "lblLast", Text = "Name: "};
container.Controls.Add(lblLast);
var lblName = new Label {ID = "lblName"};
lblName.DataBinding += delegate(object sender, EventArgs e)
{
var theLabel = (Label) sender;
var dataItem = DataBinder.GetDataItem(theLabel.BindingContainer);
theLabel.Text = DataBinder.Eval(dataItem, "LastName") + ", " +
DataBinder.Eval(dataItem, "FirstName");
};
container.Controls.Add(lblName);
}
#endregion
}