asp.net webform can't find usercontrol - asp.net

I don't know how to get usercontrol's function GetValue(), I always get Error code CS1061.
First I can't get usercontrol ID testControl.
I have found lots example, but almost example can use like my code.
I don't know what's wrong about it.
This is all my code.
User Control Part
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="testControl.ascx.cs" Inherits="MyWeb.UserControl.testControl" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<style type="text/css">
.center {
text-align: center;
}
</style>
<asp:UpdatePanel ID="upUserControl" runat="server">
<ContentTemplate>
<table>
<thead>
<tr>
<td colspan="4">
<div class="center">
<asp:Label ID="lblTitle" runat="server" Text="查詢"></asp:Label>
</div>
</td>
</tr>
</thead>
<tbody>
<tr>
<td><asp:Label ID="lblName" runat="server" Text="姓名"></asp:Label></td>
<td><asp:TextBox ID="txtName" MaxLength="10" runat="server"></asp:TextBox></td>
<td><asp:Label ID="lblIdentify" runat="server" Text="身分證字號/統編:"></asp:Label></td>
<td><asp:TextBox ID="txtIdentify" MaxLength="10" runat="server"></asp:TextBox></td>
<td><asp:Button ID="btnQuery" runat="server" Text="查詢" OnClick="btnQuery_Click"/></td>
</tr>
</tbody>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind of User Control
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyWeb.UserControl
{
public partial class testControl : System.Web.UI.UserControl
{
public string Name, Identify;
public string GetValue()
{
return txtName.Text + txtIdentify.Text;
}
protected void Page_Load(object sender, EventArgs e)
{ }
protected void btnQuery_Click(object sender, EventArgs e)
{ }
}
}
asp Page
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="testDynamicSelect.aspx.cs" Inherits="MyWeb.testDynamicSelect" %>
<%# Register Src="~/UserControl/testControl.ascx" TagPrefix="ucTest" TagName="ctrl" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<ucTest:ctrl runat="server" ID="testControl" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</asp:Content>
Code Behind of asp Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyWeb
{
public partial class testDynamicSelect : Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void Button1_Click(object sender, EventArgs e)
{
//I can't get testControl
Response.Write(testControl.GetValue());
}
}
}

I try to reference namespace MyWeb.UserControl, and it can work now.
In my company old project, it wouldn't reference just like my question.
But in my new project can't work. It have to reference namespace MyWeb.UserControl.
Who can tell me how it work?
using MyWeb.UserControl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyWeb
{
public partial class testDynamicSelect : Page
{
testControl ucl = new testControl();
//UserControl ucl = new UserControl;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Console.WriteLine(cul.GetValue());
//Button1
}
}
}

Related

My ASP.NET login page showing 'TextBox' must be placed inside a form tag with runat=server

Here is the following complete code
1) is the master page aspx
2) is the webform page aspx
3) is the webform C# file
The complete details as i suppose
now this ASP:content is already a form and also when i am adding form tag it is showing the page can have only form tage .Please can anyone help ?
Master page
<%# Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="eliblogin" runat="server" Text="Login"></asp:Label>
</form>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</body>
</html>
masterpage.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
Page.LoadComplete += new EventHandler(set_button);
}
protected void eliblogout_Click(object sender, EventArgs e)
{
var user = Context.User.Identity;
//authentication manager
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
//logout
authenticationManager.SignOut();
Response.Redirect("~/Index.aspx");
}
private void set_button(Object sender,EventArgs e)
{
var user = Context.User.Identity;
if (user.Name!=null && user.IsAuthenticated)
{
try
{
//Username.Text = user.Name;
eliblogin.Visible = true;
eliblogin.Text = "yes man you did it";
// eliblogout.Visible = true;
}
catch (Exception ex)
{
//Username.Text = ex.ToString();
}
}
else
{
// Username.Text = "Hello Guest";
eliblogin.Visible = true;
// eliblogout.Visible = false;
}
}
}
Login.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Pages_Account_Login" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Label ID="liStatus" runat="server"></asp:Label>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="username"></asp:Label><br />
<br />
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Password"></asp:Label><br />
<br />
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"> </asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Login" OnClick="Button1_Click" />
</asp:Content>
login.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 Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
public partial class Pages_Account_Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//User Store
UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();
userStore.Context.Database.Connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["elibraryConnectionString"].ConnectionString;
//User Manager
UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
//Create a new User
var user = manager.Find(txtUsername.Text,txtPassword.Text);
if (user!=null)
{
try
{
//Create user Object
//Database will be created Automatically
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var userIdentity = manager.CreateIdentity(user,DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties
{
IsPersistent=false
},userIdentity);
}
catch (Exception ex)
{
liStatus.Text = ex.ToString();
}
}
else
{
liStatus.Text = "invalid username or password";
}
}
catch (Exception ex)
{
liStatus.Text = ex.ToString();
}
}
}
You should move
<form id="form1" runat="server">
<asp:Label ID="eliblogin" runat="server" Text="Login"></asp:Label>
</form>
from master page to login.aspx page and place all asp content of login page into this form tag.

passing values in asp.net with 2 forms

i have 2 webpages Default.aspx and Default2.aspx,
once the user enters the data in Default.aspx ,
Default.aspx redirects the user to Default2.aspx with Request.QueryString,
for some reason im getting
txtUserId.Text does not exists in the current context Default.aspx.cs
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>QueryString Example in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div><b>QueryString Example</b></div><br />
<div>
<table>
<tr>
<td><b>UserId:</b></td>
<td><asp:TextBox ID="txtUserId" runat="server"/></td>
</tr>
<tr>
<td><b>UserName:</b></td>
<td><asp:TextBox ID="txtUserName" runat="server"/></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSend" Text="Send Values" runat="server" onclick="btnSend_Click"/></td>
</tr>
</table>
</div>
</form>
</body>
</html>
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 WebApplication1
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?UserId=" + txtUserId.Text + "&UserName=" + txtUserName.Text);
}
}
}
Default2.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>QueryString Example in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div><b>QueryString parameter Values in Default2.aspx Page</b></div><br />
<div><b>UserId:</b><asp:Label ID="lblUserId" runat="server"/></div><br />
<div><b>UserName:</b><asp:Label ID="lblUserName" runat="server"/></div>
</form>
</body>
</html>
Default2.aspx.cs:
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 WebForm4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblUserId.Text = Request.QueryString["UserId"];
lblUserName.Text = Request.QueryString["UserName"];
}
}
}
}
You need to make sure that your .aspx file code behind is match with your page like this:
<%# Page Language="C#" CodeBehind="WebForm2.aspx.cs" Inherits="yournamespace.WebForm2" .... %>
and your code behind class should match the CodeBehind property:
public partial class WebForm2 : System.Web.UI.Page
{
...
In the above example CodeBehind="WebForm2.aspx.cs" is pointing to class WebForm2

Custom Control with TextBox in GridView in ASP.net

I have created a Custom Control with textbox.
I am calling it in GridView. When an Update event is fired it always saves 0.
I have used following code , could any one help in the same.
Following is the code used for custom control.
ASCX Code
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ItemRequiredTextBox.ascx.cs"
Inherits="ItemRequiredTextBox" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:TextBox ID="txtWin_Delievered_Qty" runat="server" >
<asp:FilteredTextBoxExtender ID="ftbe3" runat="server" TargetControlID="txtWin_Delievered_Qty"
ValidChars="1234567890" />
<asp:CompareValidator ID="CompareValidator1" runat="server" Display="None" ValueToCompare='<%# this.Text2 %>' ControlToValidate="txtWin_Delievered_Qty" Type="Integer"
ErrorMessage="Quantity to be delievered can not be More than Required Quantity"
Operator="LessThanEqual">
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender1" TargetControlID="CompareValidator1"
runat="server">
<asp:CompareValidator ID="CompareValidator2" runat="server" Display="None" ValueToCompare='<%# this.Text1 %>' ControlToValidate="txtWin_Delievered_Qty" Type="Integer"
ErrorMessage="Quantity delievered can not be less than delievered Quantity" Operator="GreaterThanEqual">
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender2" TargetControlID="CompareValidator2"
runat="server">
ASCX.CS Code
using System;
using System.Data;
using System.ComponentModel;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class ItemRequiredTextBox : System.Web.UI.UserControl
{
[Bindable(true, BindingDirection.TwoWay)]
protected void Page_Load(object sender, EventArgs e)
{
}
private int TexT1;
private int TexT2;
public int Text1
{
get { return TexT1; }
set { TexT1 = value; }
}
public int Text2
{
get { return TexT2; }
set { TexT2 = value; }
}
public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["Text"] = value;
}
}
}
Create a public property in the usercontrol to get textbox value:
public string Text
{
get
{
return txtWin_Delievered_Qty.Text;
}
}
And access the value in the gridview update event:
ItemRequiredTextBox irtBox = (ItemRequiredTextBox)gvMyGridView.Rows[e.Item.ItemIndex].FindControl("updatedBy");
string myText = irtBox.Text;
Here gvMyGridView is your gridview

UseSubmitBehavior=False not working with OnClientClick when webform is based on a Master Page

I'm writing an admin page where I have a textbox for user name and a refresh button which shows user details when clicked. Among other controls, I have a 'remove user' button to delete the user. I have javascript code to get confirmation before attempting this.
Because I do not want this Remove User button to have submit behavior, I have set UseSubmitBehavior=False. However, this caused the server side event to not get fired. So I wrote a small client side function to explicitly call __doPostBack.
The final code works, but only on pages that are not based off of a master page or nested master pages. Sadly all my web pages are based off of master pages.
Wondering if I'm missing something or if there is a way around? I've just started asp.net so please excuse any obvious mistakes.
Many thanks in advance.
Code Sample:
Following code works (webform with no master page)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm_with_NoMasterPage.aspx.cs" Inherits="WebApplication1.WebForm_with_NoMasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<script type="text/javascript">
function GetConfirmation(btn, msg) {
if (confirm(msg)) {
__doPostBack(btn.id, '');
return true;
}
else {
return false;
}
}
</script>
<asp:Button ID="btnRemoveUser" runat="server" Text="Remove User" OnClick="btnRemoveUser_Click"
OnClientClick="return GetConfirmation(btnRemoveUser, 'Really remove?');"
UseSubmitBehavior="false"
Height="37px" Width="230px" />
</div>
</form>
</body>
</html>
code behind:
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 WebForm_with_NoMasterPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnRemoveUser_Click(object sender, EventArgs e)
{
// put a breakpoint here and see if it is hit.
int x = 0;
}
}
}
Following does not work (same fragment but in a Webform based on masterpage):
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm_WITH_MasterPage.aspx.cs" Inherits="WebApplication1.WebForm_WITH_MasterPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function GetConfirmation(btn, msg) {
if (confirm(msg)) {
__doPostBack(btn.id, '');
return true;
}
else {
return false;
}
}
</script>
<asp:Button ID="btnRemoveUser" runat="server" Text="Remove User" OnClick="btnRemoveUser_Click"
OnClientClick="return GetConfirmation(btnRemoveUser, 'Really remove?');"
UseSubmitBehavior="false"
Height="37px" Width="230px" />
</asp:Content>
Code behind:
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 WebForm_WITH_MasterPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnRemoveUser_Click(object sender, EventArgs e)
{
// put a breakpoint here and see if it is hit
int z = 0;
}
}
}

How to Add One event to each Item On A CheckboxList Asp.net

How Can I Add One Event to Each item On A CheckBoxList, pr example I Wanto to add One Click Event to check What Item Has been checked.
thanks in advance.
Each item in CheckBoxList is of type System.Web.UI.WebControls.ListItem and has no events defined.
That's a bit tricky with the CheckBoxList. Don't think there's a straight way to add an click-event to each item, since the ListItem-class doesn't have any events.
You could set AutoPostBack="true" on the CheckBoxList and check on page load which items are selected, but you wouldn't know easy which was the last one clicked.
Other solution is to get rid of the CheckBoxList and create just CheckBoxes and set the click-event on those to the same event-method. And there you could check the sender.
ASPX:
<asp:CheckBox ID="CheckBox1" Text="A" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
<asp:CheckBox ID="CheckBox2" Text="B" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
<asp:CheckBox ID="CheckBox3" Text="C" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
Code behind:
void CheckBox_CheckedChanged(object sender, EventArgs e)
{
Console.WriteLine(((CheckBox)sender).Text);
}
Or you could make your own custom CheckBoxList that handles click-events on items.
OK. So I found this question/answer and it didn't help me out. While the provided answer is correct, there is an easy way to build a CheckBoxList-like control witha Repeater control.
Turns out that you can use a Repeater with an ItemTemplate with a CheckBox.
I have a complete explanation here: http://www.rhyous.com/2014/10/17/aspx-checkboxlist-alternative-that-allows-for-the-oncheckedchanged-event/
I also copied the needed data here in this answer:
Default.aspx
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckBoxListExample._Default" %>
<%# Import Namespace="CheckBoxListExample" %>
<%# Import Namespace="CheckBoxListExample.Models" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="cb1" runat="server" AutoPostBack="true" OnCheckedChanged="RepeaterCheckBoxChanged"
Text="<%# ((CheckBoxViewModel)Container.DataItem).Name %>"
Checked="<%# ((CheckBoxViewModel)Container.DataItem).IsChecked %>" />
</ItemTemplate>
</asp:Repeater>
</div>
</asp:Content>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using CheckBoxListExample.Models;
namespace CheckBoxListExample
{
public partial class _Default : Page
{
private List<CheckBoxViewModel> _ViewModels;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var _ViewModels = new List<CheckBoxViewModel>
{
new CheckBoxViewModel {Name = "Test1", IsChecked = true},
new CheckBoxViewModel {Name = "Test2"},
new CheckBoxViewModel {Name = "Test3"}
};
Repeater1.DataSource = _ViewModels;
Repeater1.DataBind();
}
}
protected void RepeaterCheckBoxChanged(object sender, EventArgs e)
{
var cb = sender as CheckBox;
if (cb == null) return;
if (cb.Checked)
{
// Insert
}
else
{
// Delete
}
}
}
}
CheckBoxViewModel
namespace CheckBoxListExample.Models
{
public class CheckBoxViewModel
{
public string Name { get; set; }
public bool IsChecked { get; set; }
}
}

Resources