I have issues.
One of them is this one.
I'm trying to bind a list of Hyperlinks to a repeater and I think my code looks all good, but my repeater is sadly lacking in anything. It's totally blank (Apart from the header, which is not databound).
I can't see where the problem is, so I'm hoping you guys can point it out to me.
Code:
Markup
<asp:Panel ID="pnlNavMenu" class="navigation" runat="server" Visible="true">
<div class="search-textbox"><div>
<asp:ImageButton ID="btnSearch" class="Search-Icon"
BackColor="White" runat="server" OnClick="btnSearch_Click"
ImageUrl="~/images/Mobile/mobile-search-icon.png" />
<asp:TextBox ID="txtSearch" runat="server" CssClass="Search" onblur="if(this.value == '') { this.value='Enter keyword or product code'; isSet=true; }"
onmouseover="if(this.value == 'Enter keyword or product code') { this.value='';isSet = true; }"
onmouseout="if(this.value == '' && !isSet) { this.value='Enter keyword or product code'; isSet=>false; }"
MaxLength="255" Text="Enter keyword or product code" ontextchanged="btnSearch_Click"/>
<asp:ImageButton ID="btnClear" class="Search-Cancel" BackColor="White" runat="server" OnClick="btnClear_Click" ImageUrl="~/images/Mobile/mobile-search-cancel.png" />
</div>
</div>
<asp:Panel ID="pnlComputers" runat="server" CssClass="nav-item" Visible="true">
<asp:Label id="lblComp" Text="Computers" runat="server" cssclass="Menu-Panel-Header"></asp:Label>
<asp:Repeater ID="rptComputers" runat="server">
<ItemTemplate><asp:HyperLink ID="hlCompCategories" runat="server" CssClass="nav-sub-item"><%#Eval("XW_WEBCATNAME") %></asp:HyperLink></ItemTemplate>
</asp:Repeater>
</asp:Panel
<asp:CollapsiblePanelExtender ID="cpe1" runat="Server" TargetControlID="pnlComputers" CollapsedSize="64" ExpandedSize="192" Collapsed="True" ExpandControlID="lblComp" CollapseControlID="lblComp" AutoCollapse="false" AutoExpand="False" ScrollContents="True" ExpandDirection="Vertical" />
</asp:Panel>
C#
protected void Page_Init(object sender, EventArgs e)
{
if (Session["Customer"] is GPCUser)
{
hlLogInOut.Text = "Log Out";
hlLogInOut.NavigateUrl = "log-in.aspx?logout=1";
hlRegDetails.Text = "My Details";
hlRegDetails.NavigateUrl = "/update-details.aspx";
}
else
{
hlLogInOut.Text = "Log in";
hlLogInOut.NavigateUrl = "/log-in.aspx";
hlRegDetails.Text = "Register";
hlRegDetails.NavigateUrl = "/create-account.aspx";
}
BindCategories();
}
private void BindCategories()
{
if (!IsPostBack)
{
try
{
SqlConnection connect = new SqlConnection();
DataTable Data = new DataTable();
connect.ConnectionString = "SERVER = SERVER-SQL01; Trusted_Connection=yes; DATABASE=PCSQL";
connect.Open();
string query = null;
query = "SELECT * from dbo.STOCK_GROUPS WHERE XW_MAINGROUP = '1' ORDER BY XW_WEBCATNAME ASC";
SqlDataAdapter command = new SqlDataAdapter(query, connect);
command.Fill(Data);
connect.Close();
rptComputers.DataSource = Data;
}
catch (SqlException sqlEX)
{
sqlEX.ToString();
}
}
}
protected void rptComputers_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
HyperLink hlCompCategories = (HyperLink)e.Item.FindControl("hlCompCategories");
DataRowView dr = (DataRowView)e.Item.DataItem;
hlCompCategories.NavigateUrl = Page.ResolveUrl("~/" + "Computers" + "/" + dr["XW_URL"] + "/index.aspx");
if ((!object.ReferenceEquals(dr["xw_webcatname"], System.DBNull.Value)))
{
hlCompCategories.Text = (dr["xw_webcatname"]).ToString();
hlCompCategories.ToolTip = (dr["xw_webcatname"]).ToString();
}
else
{
hlCompCategories.Text = dr["groupname"].ToString();
hlCompCategories.ToolTip = dr["xw_webcatname"].ToString();
}
}
}
I'm pretty sure that the issue is in the ItemDataBound method because the rest of the panel loads fine (search bar and header, etc.) but none of my links are there.
After
rptComputers.DataSource = Data;
add
rptComputers.DataBind();
Otherwise it won't bind.
You might be missing AutoEventWireup=true in Page header in aspx file.
If not than please try to bind the repeater in the Page_Load event instead binding in Page_Init event.
Related
I have the following repeater wrapped in an Update Panel
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:Repeater ID="skillTable" runat="server">
<ItemTemplate>
<table class="table table-hover">
<tr>
<td>
<asp:ImageButton runat="server" AutoPostBack="True" ID="skillButton" OnClick="skillButton_Click" CommandArgument="<%# Eval(DropDownList1.SelectedValue)%>" class="addText btn btn-success" ImageUrl="~/img/addbut.png" /></td>
<td><asp:Label runat="server" id="skillName" Text='<%# DataBinder.Eval(Container.DataItem, DropDownList1.SelectedValue) %>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
It kicks out the information from my database perfectly, and it has a button right before the text in each row.
The problem that i have is that I need each button on each row to, when clicked, add the specific line of code in that row to a textbox.
foreach (RepeaterItem item in skillTable.Items)
{
string skill = item.DataItem.ToString();
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
}
UpdatePanel2.Update();
I have also tried this way,
protected void skillTable_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
int d = 0;
if(DropDownList1.SelectedValue == "Business and Finance")
{
d = 1;
}
else if(DropDownList1.SelectedValue == "Computers and Technology")
{
d = 2;
}
else if (DropDownList1.SelectedValue == "Education")
{
d = 3;
}
else if (DropDownList1.SelectedValue == "Customer Service")
{
d = 4;
}
DataRowView drv = (DataRowView)e.Item.DataItem;
string skill = drv[d].ToString();
Session["Table"] = skill;
}
protected void skillButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
string skill = (string)(Session["Table"]);
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
UpdatePanel2.Update();
}
but neither one of them seems to work correctly. Any advice? I havent really used repeaters before this, so If there is any other tool that would work better, I'm open for suggestions.
Thanks in advance!
So I figured it out. What I was missing was a way for my site to specifically narrow down what i needed. I added the code blow to my click method and got rid of the ItemDataBound method and it worked like a charm.
Button button = (sender as Button);
string commandArgument = button.CommandArgument;
RepeaterItem item = button.NamingContainer as RepeaterItem;
var workText = (Label)item.FindControl("workName1") as Label;
string work = workText.Text;
string text = workDetails1.Text;
if (text == " ")
text = "";
if (text == "")
{
if (!text.Contains(work))
{
text +="\u2022 " + work;
workDetails1.Text = text;
}
}
else if (!string.IsNullOrEmpty(work))
{
if (!text.Contains(work))
{
text += "\n\u2022 " + work;
workDetails1.Text = text;
}
else
{
workDetails1.Text = text;
}
}
UpdatePanel4.Update();
Hope this helps someone!
I`m trying to make an ASP.NET basic site that connects to a database. It's supposed to allow a user to register and log in.
I check the input with javascript and in the code behind in case it's disabled.
The problem is that whenever i click the register, login, or logout buttons for the first time they won't work; The page remains the same.
The second time, however, they work perfectly.
Debugger says it's called both times.
any ideas?
ASP:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs"
Inherits="Register_and_Login.Main" %>
<!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">
<script type="text/javascript">
function isUserValid() {
var UserLength = document.getElementById("UserTB").value.length;
var ValidatorLabel = document.getElementById("ValidateUser");
if (UserLength < 6 || UserLength > 15) {
ValidatorLabel.style.display = 'inline';
return false;
}
else {
ValidatorLabel.style.display = 'none';
return true;
}
}
function isPassValid() {
var PassLength = document.getElementById("PasswordTB").value.length;
var ValidatorLabel = document.getElementById("ValidatePassword");
if (PassLength < 6 || PassLength > 15) {
ValidatorLabel.style.display = 'inline';
return false;
}
else {
ValidatorLabel.style.display = 'none';
return true;
}
}
function isConfirmValid() {
var Password = document.getElementById("PasswordTB").value;
var Me = document.getElementById("ConfirmTB").value;
var ValidatorLabel = document.getElementById("ValidateConfirm");
if (Password == Me) {
ValidatorLabel.style.display = 'none';
return true;
}
else {
ValidatorLabel.style.display = 'inline';
return false;
}
}
function isEmailValid() {
var str = document.getElementById("EmailTB").value;
var lastAtPos = str.lastIndexOf('#');
var lastDotPos = str.lastIndexOf('.');
var isFine = (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('##') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
var ValidationLabel=document.getElementById("ValidateEmail");
if(isFine)
{
ValidationLabel.style.display='none';
return true;
}
else
{
ValidationLabel.style.display='inline';
return false;
}
}
</script>
<title></title>
<style type="text/css">
.Validators
{
display:none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel id="RegisterRelated" runat="server">
Username:<br />
<asp:TextBox ID="UserTB" runat="server" OnChange="isUserValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateUser" runat="server" ForeColor="Red"
Text="Username must be 6-15 characters in length, and contain no special characters." CssClass="Validators"></asp:Label>
<br />
Password:<br />
<asp:TextBox ID="PasswordTB" runat="server" OnChange="isPassValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidatePassword" runat="server" ForeColor="Red"
Text="Password must be 6-15 characters in length, and contain no special characters." CssClass="Validators"></asp:Label>
<br />
Confirm password:<br />
<asp:TextBox ID="ConfirmTB" runat="server" OnChange="isConfirmValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateConfirm" runat="server" ForeColor="Red"
Text="This field must match the password field." CssClass="Validators"></asp:Label>
<br />
Email:<br />
<asp:TextBox ID="EmailTB" runat="server" OnChange="isEmailValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateEmail" runat="server" ForeColor="Red" Text="Invalid Email." CssClass="Validators"></asp:Label>
<br />
<br />
<asp:Button ID="Register" runat="server" Text="Register" onclick="Register_Click" EnableViewState="false"/>
<br />
<asp:Panel ID="Answer" runat="server" >
</asp:Panel>
</asp:Panel>
<br />
<br />
<asp:Panel id="LoginRelated" runat="server">
User:
<asp:TextBox ID="LoginUserTB" runat="server" AutoPostBack="false"></asp:TextBox>
<br />
Password:
<asp:TextBox ID="LoginPassTB" runat="server" AutoPostBack="false"></asp:TextBox>
<br />
<asp:Button ID="Login" runat="server" Text="Login" onclick="Login_Click" EnableViewState="false" />
<br />
</asp:Panel>
<asp:Panel ID="InPage" runat="server">
<asp:Panel ID="LogAnswer" runat="server">
</asp:Panel>
<br />
<asp:Label ID="WelcomeTag" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="logout" runat="server" onclick="logout_Click" Text="Logout" EnableViewState="false"/>
</asp:Panel>
</div>
</form>
</body>
</html>
C# Login, Logout & Register buttons:
protected void Register_Click(object sender, EventArgs e)
{
Label Reply = new Label();
if (Session["User"] == null)
{
Result myRegResult = Result.IN_PROG;
User myAddedUser = new User(UserTB.Text, PasswordTB.Text, EmailTB.Text);
DbManager.OpenDbConnection();
myRegResult = DbManager.Register(myAddedUser); //Connection with the database.
Reply.Text = resultToString(myRegResult);
Reply.ForeColor = resultColor(myRegResult);
}
else
{
Reply.Text = "You must log out before you register.";
Reply.ForeColor = resultColor(Result.EXEC_ERROR);
}
Answer.Controls.Add((Control)Reply);
//Reset_Fields();
}
protected void Login_Click(object sender, EventArgs e)
{
Label Reply = new Label();
LoginProc Status = LoginProc.IN_PROG;
DbManager.OpenDbConnection();
Status = DbManager.Login(LoginUserTB.Text, LoginPassTB.Text); //Connection with the database
Reply.Text = ProcToString(Status);
Reply.ForeColor = ProcToColor(Status);
LogAnswer.Controls.Add(Reply);
if (Status == LoginProc.FINE)
Session["User"] = new User(LoginUserTB.Text, LoginPassTB.Text, null);
//Reset_Fields();
}
protected void logout_Click(object sender, EventArgs e)
{
Session["User"] = null;
}
Page load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
EDIT: A friend of mine adviced me to take a look in the ASP.NET page lifecycle, and it might have something to do with the database interactions being done after the page is presented, if it helps anyone.
Your friend is correct, you need to understand the page the Page Life cycle better. Basically in this instance you need to understand that the OnLoad event happens before any click events. You can see this for yourself by adding a break point to the OnLoad event and the click handler. You will see that the order of events as they happen.
In this instance I would writ a method to set up the page, and then call this in each of the on click events
private void setUpPage()
{
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Call if not in response to button click
if(!IsPostBack)
{
setUpPage();
}
}
protected void Register_Click(object sender, EventArgs e)
{
Label Reply = new Label();
if (Session["User"] == null)
{
Result myRegResult = Result.IN_PROG;
User myAddedUser = new User(UserTB.Text, PasswordTB.Text, EmailTB.Text);
DbManager.OpenDbConnection();
myRegResult = DbManager.Register(myAddedUser); //Connection with the database.
Reply.Text = resultToString(myRegResult);
Reply.ForeColor = resultColor(myRegResult);
}
else
{
Reply.Text = "You must log out before you register.";
Reply.ForeColor = resultColor(Result.EXEC_ERROR);
}
Answer.Controls.Add((Control)Reply);
//Reset_Fields();
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
protected void Login_Click(object sender, EventArgs e)
{
Label Reply = new Label();
LoginProc Status = LoginProc.IN_PROG;
DbManager.OpenDbConnection();
Status = DbManager.Login(LoginUserTB.Text, LoginPassTB.Text); //Connection with the database
Reply.Text = ProcToString(Status);
Reply.ForeColor = ProcToColor(Status);
LogAnswer.Controls.Add(Reply);
if (Status == LoginProc.FINE)
Session["User"] = new User(LoginUserTB.Text, LoginPassTB.Text, null);
//Reset_Fields();
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
protected void logout_Click(object sender, EventArgs e)
{
Session["User"] = null;
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
When you click the login or register button, page load event works firstly, and after button click event works.
I can see that, you set to page display in page load event and set to Session value in button click event. So at first click, page load event triggered first, but there is no Session value yet. Page load event finishes and resume with button click event, so Session value is not null now (if entered user info is valid).
It is the reason why page work at second click.
Solution:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack) //just write this
return;
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
Note: I got your code and tried.
Also see this: http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.85%29.aspx
I think there is issue with validators. Please set causes validation property of buttons according to your requirements.
Try Page_BlockSubmit = false; before every return false;
I have tried to build one gridview with dynamic columns based the data source using the template fields in asp.net through code behind.
For that, to implement we have developed one class DynamicTemplate which implements the ITemplate interface. In that template fields i have inserted the LinkButton in each cell and when i click that cell link button i need to show the one Popup with selected cell value.
For Detailed Sample Please download from this link
For that I have created one Default.asxp page and wrote the following.
public partial class Default : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
}
private void GenateGridView()
{
TemplateField tempField;
DynamicTemplate dynTempItem;
LinkButton lnkButton;
Label label;
GridView gvDynamicArticle = new GridView();
gvDynamicArticle.Width = Unit.Pixel(500);
gvDynamicArticle.BorderWidth = Unit.Pixel(0);
gvDynamicArticle.Caption = "<div>Default Grid</div>";
gvDynamicArticle.AutoGenerateColumns = false;
DataTable data = getBindingData();
for (int i = 0; i < data.Columns.Count; i++)
{
tempField = new TemplateField();
dynTempItem = new DynamicTemplate(ListItemType.AlternatingItem);
lnkButton = new LinkButton();
lnkButton.ID = string.Format("lnkButton{0}", i);
lnkButton.Visible = true;
string ColumnValue = data.Columns[i].ColumnName;
tempField.HeaderText = ColumnValue;
if (ColumnValue == "EmpName")
{
label = new Label();
label.ID = string.Format("Label{0}", i);
dynTempItem.AddControl(label, "Text", ColumnValue);
label.Width = 100;
}
else
{
dynTempItem.AddControl(lnkButton, "Text", ColumnValue);
lnkButton.Click += lnkButton_Click;
}
tempField.ItemTemplate = dynTempItem;
gvDynamicArticle.Columns.Add(tempField);
//////grdUserPivotDateTwo.Columns.Add(tempField);
}
gvDynamicArticle.DataSource = data;
gvDynamicArticle.DataBind();
divContainer.Controls.Add(gvDynamicArticle);
}
void lnkButton_Click(object sender, EventArgs e)
{
// showing cell values in popUp here..
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('cell clicked')");
}
private DataTable getBindingData()
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("EmpName"));
dt.Columns.Add(new DataColumn("Monday"));
dt.Columns.Add(new DataColumn("TuesDay"));
dt.Columns.Add(new DataColumn("WednesDay"));
dt.Columns.Add(new DataColumn("ThursDay"));
dt.Rows.Add("EmpOne", "p", "p", "p", "a");
dt.Rows.Add("EmpTwo", "p", "a", "p", "p");
dt.Rows.Add("EmpThree", "p", "p", "p", "a");
dt.Rows.Add("EmpFour", "p", "a", "p", "p");
dt.Rows.Add("EmpFive", "p", "p", "p", "a");
dt.Rows.Add("EmpSix", "a", "p", "p", "p");
return dt;
}
}
and corresponding DynamicTemplate class is
public class DynamicTemplate : System.Web.UI.ITemplate
{
System.Web.UI.WebControls.ListItemType templateType;
System.Collections.Hashtable htControls = new System.Collections.Hashtable();
System.Collections.Hashtable htBindPropertiesNames = new System.Collections.Hashtable();
System.Collections.Hashtable htBindExpression = new System.Collections.Hashtable();
public DynamicTemplate(System.Web.UI.WebControls.ListItemType type)
{
templateType = type;
}
public void AddControl(WebControl wbControl, String BindPropertyName, String BindExpression)
{
htControls.Add(htControls.Count, wbControl);
htBindPropertiesNames.Add(htBindPropertiesNames.Count, BindPropertyName);
htBindExpression.Add(htBindExpression.Count, BindExpression);
}
public void InstantiateIn(System.Web.UI.Control container)
{
PlaceHolder ph = new PlaceHolder();
for (int i = 0; i < htControls.Count; i++)
{
//clone control
Control cntrl = CloneControl((Control)htControls[i]);
switch (templateType)
{
case ListItemType.Header:
break;
case ListItemType.Item:
ph.Controls.Add(cntrl);
break;
case ListItemType.AlternatingItem:
ph.Controls.Add(cntrl);
ph.DataBinding += new EventHandler(Item_DataBinding);
break;
case ListItemType.Footer:
break;
}
}
ph.DataBinding += new EventHandler(Item_DataBinding);
container.Controls.Add(ph);
}
public void Item_DataBinding(object sender, System.EventArgs e)
{
PlaceHolder ph = (PlaceHolder)sender;
GridViewRow ri = (GridViewRow)ph.NamingContainer;
for (int i = 0; i < htControls.Count; i++)
{
if (htBindPropertiesNames[i].ToString().Length > 0)
{
Control tmpCtrl = (Control)htControls[i];
String item1Value = (String)DataBinder.Eval(ri.DataItem, htBindExpression[i].ToString());
Control ctrl = ph.FindControl(tmpCtrl.ID);
Type t = ctrl.GetType();
System.Reflection.PropertyInfo pi = t.GetProperty(htBindPropertiesNames[i].ToString());
pi.SetValue(ctrl, item1Value.ToString(), null);
}
}
}
private Control CloneControl(System.Web.UI.Control src_ctl)
{
Type t = src_ctl.GetType();
Object obj = Activator.CreateInstance(t);
Control dst_ctl = (Control)obj;
PropertyDescriptorCollection src_pdc = TypeDescriptor.GetProperties(src_ctl);
PropertyDescriptorCollection dst_pdc = TypeDescriptor.GetProperties(dst_ctl);
for (int i = 0; i < src_pdc.Count; i++)
{
if (src_pdc[i].Attributes.Contains(DesignerSerializationVisibilityAttribute.Content))
{
object collection_val = src_pdc[i].GetValue(src_ctl);
if ((collection_val is IList) == true)
{
foreach (object child in (IList)collection_val)
{
Control new_child = CloneControl(child as Control);
object dst_collection_val = dst_pdc[i].GetValue(dst_ctl);
((IList)dst_collection_val).Add(new_child);
}
}
}
else
{
dst_pdc[src_pdc[i].Name].SetValue(dst_ctl, src_pdc[i].GetValue(src_ctl));
}
}
return dst_ctl;
}
}
Here the Data showing in gridview is fine. Here the Issues are when i click on the linkButton the page reloads and no grid is displaying after the postback.
second issue is, for LinkButton the Click Event is not firing.
Please provide me the help full information/Sample to show the modal window when we click on the linkButton of the gridview.
You need to use ajax model popup expender.
Design a panel with your fields and use the model popup expender to display that popup
This link has the sample of it
www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/modalpopup/modalpopup.aspx
and in your link button click
you have to use show method to open popup
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
}
this code is generating a gridview only if it is not a postback, but when you click a linkbutton a postpack occurs and that's the reason why gridview doesnt show again when you click on the linkbutton.
add the following code(additional else part included to your if code) to show gridview when you click lnkButton
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
else
{
string ctrlName = Request.Params.Get("__EVENTTARGET").Trim();
if (!String.IsNullOrEmpty(ctrlName))
{
if (ctrlName.StartsWith("lnkButton"))
{
GenateGridView();
}
}
}
}
It will be a good choice to use CommandName property for the linkbutton on the Gridview and give it a specfic name and in the code file and exactly work with it in RowCommand event of your GridView as following in this example :
first here is the .aspx file :
<div>
<asp:GridView ID="GridViewStudents" runat="server" AutoGenerateColumns="False" OnRowCommand="GridViewStudents_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Stud_ID" Visible="False">
<ItemTemplate>
<asp:Label ID="LabelStudID" runat="server" Text='<%# Eval("Stud_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FKFather_ID" Visible="False">
<ItemTemplate>
<asp:Label ID="LabelFkFatherID" runat="server" Text='<%# Eval("Fk_Father_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Name">
<ItemTemplate>
<asp:Label ID="LabelStudName" runat="server" Text='<%# Eval("Stud_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Class Name">
<ItemTemplate>
<asp:Label ID="LabelRowlevelName" runat="server" Text='<%# Eval("Stud_Level_Row_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonDelete" runat="server" CommandArgument='<%# Eval("Stud_ID") %>' CommandName="Remove" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div style="direction: ltr">
<asp:Panel ID="Panel1" runat="server" Visible="false">
<asp:Label ID="Labelpopupmessage" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="Buttonaccept" runat="server" Text="نعم" OnClick="Buttonaccept_Click" />
<asp:Button ID="Buttoncancel" runat="server" Text="لا" OnClick="Buttoncancel_Click" />
</asp:Panel>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:ModalPopupExtender runat="server" ID="ModalPopupExtenderStudent" PopupControlID="ButtonSubmit" TargetControlID="HiddenField1" CancelControlID="Buttoncancel">
</asp:ModalPopupExtender>
</div>
and here is the code implementation of my illustration :
protected void GridViewStudents_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Remove")
{
// I stored the ID of the selected Student I want to delete in a viewstate.
ViewState.Add("DeletedStudDetailID",Convert.ToInt32(e.CommandArgument));
ModalpopupExtender.Show();
}
}
// Here in the accept delete button I used that code ..
protected void Buttonaccept_Click(object sender, EventArgs e)
{
try
{
if (ViewState["DeletedStudDetailID"] != null)
{
StudentDetail StudDet = Data.StudentDetails.Single(SD => SD.Fk_Stud_ID == Convert.ToInt32(ViewState["DeletedStudDetailID"]));
Data.StudentDetails.DeleteOnSubmit(StudDet);
Student Stud = Data.Students.Single(S => S.Stud_ID == Convert.ToInt32(ViewState["DeletedStudDetailID"]));
Data.Students.DeleteOnSubmit(Stud);
Data.SubmitChanges();
}
this.ResultMessage = "Delete Done Sucessfully !!";
}
catch
{
this.ErrorMessage = "Delete operation disordered !!";
}
finally
{
ModalPopExtender.Hide();
}
}
I hope it helps in your issue and I wish you a happy day :) !!
First, your GridView will be created when calling GenateGridView method, so you have to call this method everytime you do post back, then your Page_Load should be
protected void Page_Load(object sender, EventArgs e)
{
GenateGridView();
}
Second, I would present you the other way to add LinkButton to GridView dynamically.
I modified your GenateGridView to just add only label into DynamicTemplate, also add this line gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(gvDynamicArticle_RowDataBound); to handle adding LinkButton.
private void GenateGridView()
{
TemplateField tempField;
DynamicTemplate dynTempItem;
Label label;
GridView gvDynamicArticle = new GridView();
gvDynamicArticle.Width = Unit.Pixel(500);
gvDynamicArticle.BorderWidth = Unit.Pixel(0);
gvDynamicArticle.Caption = "<div>Default Grid</div>";
gvDynamicArticle.AutoGenerateColumns = false;
gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(gvDynamicArticle_RowDataBound);
DataTable data = getBindingData();
for (int i = 0; i < data.Columns.Count; i++)
{
tempField = new TemplateField();
dynTempItem = new DynamicTemplate(ListItemType.AlternatingItem);
string ColumnValue = data.Columns[i].ColumnName;
tempField.HeaderText = ColumnValue;
label = new Label();
label.ID = string.Format("Label{0}", i);
dynTempItem.AddControl(label, "Text", ColumnValue);
label.Width = 100;
tempField.ItemTemplate = dynTempItem;
gvDynamicArticle.Columns.Add(tempField);
}
gvDynamicArticle.DataSource = data;
gvDynamicArticle.DataBind();
divContainer.Controls.Add(gvDynamicArticle);
}
I implement like this in RowDataBound event handler of the GridView to add LinkButton and hide the Label which we added it before:
protected void gvDynamicArticle_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int j = 1; j < e.Row.Cells.Count; j++)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkButton = new LinkButton();
lnkButton.ID = string.Format("lnkButton{0}{1}", e.Row.DataItemIndex, j);
lnkButton.Click += new EventHandler(lnkButton_Click);
Label tempLabel = e.Row.FindControl("Label" + j) as Label;
lnkButton.Text = tempLabel.Text;
lnkButton.CommandArgument = tempLabel.Text;
tempLabel.Visible = false;
e.Row.Cells[j].Controls.Add(lnkButton);
}
}
}
You can also set any value to CommandArgument of LinkButton, then you can show it in the alert.
Final, seems you want to show some value in the alert, you may code like this
public void lnkButton_Click(object sender, EventArgs e)
{
// showing cell values in popUp here..
LinkButton lnk = (LinkButton)sender;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('cell clicked, value " + lnk.CommandArgument + "')", true);
}
I am trying to fire the checkbox checkedchanged event but nothing seems to work. Am I missing something here in the following code. I think I have fulfilled all the necessary conditions. So what can be wrong?
<asp:UpdatePanel ID="UpdatePanelApprove" runat="server" RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label runat="server" ID="LabelApproved" Font-Bold="true" ForeColor="Green"></asp:Label>
<asp:CheckBox runat="server" ID="CheckBoxApprove" Text="Approve?" OnCheckedChanged="CheckBoxApprove_CheckedChanged" AutoPostBack="True"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID ="CheckBoxApprove" EventName="CheckedChanged" />
</Triggers>
</asp:UpdatePanel>
edit
the code in C#
protected void CheckBoxApprove_CheckedChanged(object sender, EventArgs e)
{
CheckBox CheckBoxApprove = (CheckBox)sender;
GridViewRow row = (GridViewRow)CheckBoxApprove.Parent.Parent.Parent;
HiddenField HiddenFieldAnswerId = (HiddenField)row.FindControl("HiddenFieldAnswerId");
HiddenField HiddenFieldExpertId = (HiddenField)row.FindControl("HiddenFieldExpertId");
Label LabelApproved = (Label)row.FindControl("LabelApproved");
UpdatePanel UpdatePanelApprove =(UpdatePanel) row.FindControl("UpdatePanelApprove");
int AnswerSubjectId = AnswerDataAccess.GetSubjectIdForAnswer(Convert.ToInt32(HiddenFieldAnswerId.Value));
if (!AnswerDataAccess.CheckAnswerApprovalStatus(Convert.ToInt32(HiddenFieldAnswerId.Value)))
{
if (AnswerDataAccess.ApproveAnswer(Convert.ToInt32(HiddenFieldAnswerId.Value)))
{
if (HiddenFieldExpertId.Value != Membership.GetUser().ProviderUserKey.ToString())
{
NotificationsAccess.InsertNotification(AnswerSubjectId, null, Convert.ToInt32(HiddenFieldAnswerId.Value), null, "Approved your answer", new Guid(Membership.GetUser().ProviderUserKey.ToString()), new Guid(HiddenFieldExpertId.Value));
}
LabelApproved.Text = "Approved";
}
}
else
{
if (AnswerDataAccess.DisapproveAnswer(Convert.ToInt32(HiddenFieldAnswerId.Value)))
{
LabelApproved.Text = "";
}
}
UpdatePanelApprove.Update();
}
pageload code
protected void Page_Load(object sender, EventArgs e)
{
HtmlGenericControl Tabs = (HtmlGenericControl)this.Master.FindControl("divTabs");
Tabs.Style[HtmlTextWriterStyle.Display] = "block";
Tabs.Style["border"] = "1px solid #eee";
Tabs.InnerText = "some text";
Tabs.Style["font-size"] = "10px";
if(!IsPostBack )
{
DataTable UserS=ProfileDataAccess.GetUserS (Membership.GetUser().ProviderUserKey.ToString());
DropDownListS.DataSource=UserS;
DropDownListS.DataValueField ="SId";
DropDownListS.DataTextField="Sub";
DropDownListS.DataBind();
ListItem item= new ListItem("Select-s", "0");
item.Selected = true;
DropDownListS.Items.Add(item);
}
}
Het Try this property EnableViewState="true" in checkbox control.
I have a TabContainer in my aspx page as follows
<asp:TabContainer ID="tabcontainer" runat="server" ActiveTabIndex="0">
</asp:TabContainer>
am creating the tabs for the above containter using C# code on Oninit event of the page
protected override void OnInit(EventArgs e)
{
lstCategories = Service.GetCategories();
numberOfCategories = lstCategories.Count;
CreateTabs();
base.OnInit(e);
}
protected void CreateTabs()
{
try
{
for (int i = 0; i < numberOfCategories; i++)
{
TabPanel asptab = new TabPanel();
asptab.ID = lstCategories[i].Id.ToString();
asptab.HeaderText = lstCategories[i].Name;
MyCustomTemplate obj = new MyCustomTemplate(lstCategories[i].Id);
asptab.ContentTemplate = obj;
tabcontainer.Tabs.Add(asptab);
}
}
catch (Exception ex)
{
}
}
public class MyCustomTemplate : ITemplate
{
public Table tbl;
public TextBox tbxQuantity;
public Image img;
public int countOfItemsPerRow = 2;
public MyCustomTemplate(int paramCategoryID)
{
categoryID = paramCategoryID;
}
public void InstantiateIn(Control container)
{
InitialiseTheProperties();
container.Controls.Add(tblHardware);
}
public Table InitialiseTheProperties()
{
//Intialize the Mater Table
tbl = new Table();
//Create Row for the mater Table
TableRow row = new TableRow();
TableCell cell = new TableCell();
img = new Image();
img.ImageUrl = HttpRuntime.AppDomainAppVirtualPath +"/Images/"+"1.jpg";
cell.Controls.Add(img);
tblHardware.Rows.cells.add(cell);
tbxQuantity = new TextBox();
tbxQuantity.ID ="TbxQuantity";
cell.Controls.Add(tbxQuantity);
tblHardware.Rows.cells.add(cell);
tblHardware.Rows.Add(row);
//return tbl;
}
}
}
now am trying to this on a btnclickevent
public void btnSave_Click(object sender, EventArgs e)
{
try
{
Control cntrl = Page.FindControl("TbxQuantity");
}
catch (Exception ex)
{
}
}
it just returns null. Am i doing something wrong? Kindly Help
As i found the answer to the above question posted by myself, I would like to help fellow folks who encounter the same or similar problem.
string strQuantity=((System.Web.UI.WebControls.TextBox)(((AjaxControlToolkit.TabContainer)(BTN.Parent.FindControl("tabcontainer"))).Tabs[0].FindControl("TbxQuantity"))).Text
Thank you "Stackoverflow" for maintaining the site and I also thank the members who help developers like me.
Your issue isn't with the dynamically added controls, but that the FindControl method doesn't propogate and check all the way down the children stack.
I made a quick helper method below that checks the children until it finds the right control. It was a quick build, so it probably can be improved upon, I haven't tried but you could probably extend the control so you don't have to pass in an initial control. I tested it, however for some reason I couldn't get it to work passing in the Page object, I had to pass in the initial panel I used, but it should get the point across.
Control Finder
public static class ControlFinder
{
public static Control Find(Control currentControl, string controlName)
{
if (currentControl.HasControls() == false) { return null; }
else
{
Control ReturnControl = currentControl.FindControl(controlName);
if (ReturnControl != null) { return ReturnControl; }
else
{
foreach (Control ctrl in currentControl.Controls)
{
ReturnControl = Find(ctrl, controlName);
if (ReturnControl != null) { break; }
}
}
return ReturnControl;
}
}
}
HTML Page
<asp:Panel ID="pnl1" runat="server">
<asp:TextBox ID="pnl1_txt1" runat="server" />
<asp:TextBox ID="pnl1_txt2" runat="server" />
<asp:Panel ID="pnl2" runat="server">
<asp:TextBox ID="pnl2_txt1" runat="server" />
<asp:TextBox ID="pnl2_txt2" runat="server" />
<asp:Panel ID="pnl3" runat="server">
<asp:TextBox ID="pnl3_txt1" runat="server" />
<asp:TextBox ID="pnl3_txt2" runat="server" />
</asp:Panel>
</asp:Panel>
</asp:Panel>
<asp:Button ID="btnGo" Text="Go" OnClick="btnGo_Click" runat="server" />
<asp:Panel ID="pnlResults" runat="server">
<div>pnl1_txt1: <asp:Label ID="lblpnl1txt1" runat="server" /></div>
<div>pnl1_txt2: <asp:Label ID="lblpnl1txt2" runat="server" /></div>
<div>pnl2_txt1: <asp:Label ID="lblpnl2txt1" runat="server" /></div>
<div>pnl2_txt2: <asp:Label ID="lblpnl2txt2" runat="server" /></div>
<div>pnl3_txt1: <asp:Label ID="lblpnl3txt1" runat="server" /></div>
<div>pnl3_txt2: <asp:Label ID="lblpnl3txt2" runat="server" /></div>
<div>unknown: <asp:Label ID="lblUnknown" runat="server" /></div>
</asp:Panel>
Button Click event
protected void btnGo_Click(object sender, EventArgs e)
{
Control p1t1 = ControlFinder.Find(pnl1, "pnl1_txt1");
Control p1t2 = ControlFinder.Find(pnl1, "pnl1_txt2");
Control p2t1 = ControlFinder.Find(pnl1, "pnl2_txt1");
Control p2t2 = ControlFinder.Find(pnl1, "pnl2_txt2");
Control p3t1 = ControlFinder.Find(pnl1, "pnl3_txt1");
Control p3t2 = ControlFinder.Find(pnl1, "pnl3_txt2");
Control doesntexist = ControlFinder.Find(pnl1, "asdasd");
lblpnl1txt1.Text = p1t1 != null ? "Found: " + p1t1.ID : "Not found";
lblpnl1txt2.Text = p1t2 != null ? "Found: " + p1t2.ID : "Not found";
lblpnl2txt1.Text = p2t1 != null ? "Found: " + p2t1.ID : "Not found";
lblpnl2txt2.Text = p2t2 != null ? "Found: " + p2t2.ID : "Not found";
lblpnl3txt1.Text = p3t1 != null ? "Found: " + p3t1.ID : "Not found";
lblpnl3txt2.Text = p3t2 != null ? "Found: " + p3t2.ID : "Not found";
lblUnknown.Text = doesntexist != null ? "Found: " + doesntexist.ID : "Not found";
}