Sum values in dynamic control asp net - c#

I have created a dynamic control script. What I want to do is to Sum all "LabelVlera" that is in "Details.ascx" in a single Label that is "LabelTotal" in ".aspx.cs file".
I hope you understood me. thank you.
On the UserControl Folder I have this script...
Details.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ContactDetails.ascx.cs" Inherits="UserControl_ContactDetails" EnableViewState="false" %>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
width: 150px;
}
.auto-style3 {
width: 294px;
}
.auto-style4 {
width: 150px;
text-align: right;
}
</style>
<table class="auto-style1">
<tr>
<td class="auto-style4">
<asp:Label ID="Label1" runat="server" Text="Artikulli:"></asp:Label>
</td>
<td class="auto-style3">
<asp:DropDownList ID="DropDownListArtikulli" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownListArtikulli_SelectedIndexChanged">
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="DropDownListArtikulli" ErrorMessage="Zgjidhni artikullin"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="Label2" runat="server" Text="Cmimi:"></asp:Label>
</td>
<td class="auto-style3">
<asp:Label ID="LabelCmimi" runat="server"></asp:Label>
<asp:Label ID="Label3" runat="server" Text="lek"></asp:Label>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="Label4" runat="server" Text="Sasia:"></asp:Label>
</td>
<td class="auto-style3">
<asp:TextBox ID="TextBoxSasia" runat="server" AutoPostBack="True"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBoxSasia" ErrorMessage="Vendosni sasine"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="Label5" runat="server" Text="Vlera:"></asp:Label>
</td>
<td class="auto-style3">
<asp:Label ID="LabelVlera" runat="server" ></asp:Label>
<asp:Label ID="Label6" runat="server" Text="lek"></asp:Label>
</td>
<td> </td>
</tr>
</table>
<hr />
Details.ascx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class UserControl_ContactDetails : System.Web.UI.UserControl
{
#region Public Properties
public Label VlTotal
{
get
{
return LabelVlera;
}
set
{
LabelVlera = value;
}
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
DropDownListArtikulli.Text = Request.Form[DropDownListArtikulli.UniqueID];
LabelCmimi.Text = Request.Form[LabelCmimi.UniqueID];
TextBoxSasia.Text = Request.Form[TextBoxSasia.UniqueID];
LabelVlera.Text = Request.Form[LabelVlera.UniqueID];
}
Cmimi();
Vlera();
}
private void Cmimi()
{
DataTable listaArtikujt = new DataTable();
using (SqlConnection lidhje = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM [Artikujt]", lidhje);
adapter.Fill(listaArtikujt);
DropDownListArtikulli.DataSource = listaArtikujt;
DropDownListArtikulli.DataTextField = "Artikulli";
DropDownListArtikulli.DataValueField = "Cmimi";
DropDownListArtikulli.DataBind();
LabelCmimi.Text = DropDownListArtikulli.SelectedValue.ToString();
}
catch (Exception ex)
{
Response.Write("Gabim:" + ex.ToString());
}
}
}
protected void DropDownListArtikulli_SelectedIndexChanged(object sender, EventArgs e)
{
Cmimi();
}
private void Vlera()
{
if(!string.IsNullOrEmpty(TextBoxSasia.Text))
{
LabelVlera.Text = TextBoxSasia.Text.ToString();
int a = Convert.ToInt32(LabelCmimi.Text);
int b = Convert.ToInt32(LabelVlera.Text);
int c = a * b;
LabelVlera.Text = c.ToString();
}
}
protected void TextBoxSasia_TextChanged(object sender, EventArgs e)
{
Vlera();
}
}

Related

How to delete specific listview items in ASP.NET C#?

Here is my messageview.aspx, which has list view to show user messages.
On delete button click, I want to capture the current table row value, and call the sql stored procedure accordingly. However, I am unable to access the fields like Sender Email-ID, Sender Role, and Message inside delete button click function. how can I do so?
<%# Page Title="" Language="C#" MasterPageFile="~/DefaultLayout.Master" AutoEventWireup="true" CodeBehind="MessageView.aspx.cs" Inherits="SchoolMgmtSystem.MessageView" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="jumbotron">
<h1>Inbox</h1>
</div>
<asp:ListView ID="lvgetMessages" runat="server" OnSelectedIndexChanged="lvgetMessages_SelectedIndexChanged">
<EmptyDataTemplate>
<table runat="server" style="background-color: #FFFFFF; border-collapse: collapse; border-color: #999999; border-style: none; border-width: 1px;">
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<LayoutTemplate>
<table class="table table-border">
<tr>
<th> Sender Email ID</th>
<th> Sender Role </th>
<th> Message</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style="background-color: #DCDCDC; color: #000000;">
<td>
<asp:Label ID="emailIDLabel" runat="server" Text='<%# Eval("[SenderEmailID]") %>' />
</td>
<td>
<asp:Label ID="SenderRoleLabel" runat="server" Text='<%# Eval("RoleName") %>' />
</td>
<td>
<asp:Label ID="MessageLabel" runat="server" Text='<%# Eval("[Message]") %>' />
</td>
<td>
<asp:Button ID="ButtonDelete" runat="server" Text="Delete" onclick="ButtonDelete_Click" UseSubmitBehavior="False" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<div class="form-group" runat="server" style="display:block">
<asp:Button ID="ButtonBack" runat="server" Text="Back" CssClass="btn-primary center-block" OnClick="ButtonBack_Click" />
</div>
</asp:Content>
The code behind message view is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BAL;
using System.Data;
namespace SchoolMgmtSystem
{
public partial class MessageView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lvgetMessages.DataSource = null;
lvgetMessages.DataBind();
String roleId = Request.QueryString["RoleId"];
String userId = Request.QueryString["UserId"];
String userEmailId = AdminBizz.GetEmailId(userId, roleId);
DataTable dtMessageInfo = RoleBizz.GetUserMessages(userEmailId);
if (dtMessageInfo.Rows.Count > 0)
{
lvgetMessages.DataSource = dtMessageInfo;
lvgetMessages.DataBind();
}
}
protected void lvgetMessages_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ButtonDelete_Click(object sender, EventArgs e)
{
}
protected void ButtonBack_Click(object sender, EventArgs e)
{
String roleId = Request.QueryString["RoleId"];
String userId = Request.QueryString["UserId"];
Response.Redirect("MessageSend.aspx?UserId=" + userId + "&RoleId=" + roleId);
}
}
}
Here is the screen shot -
What you can probably do is get the NamingContainer of your delete button and find the other controls within it.
protected void ButtonDelete_Click(object sender, EventArgs e)
{
var control = (Control)sender;
var container = control.NamingContainer;
// access your controls this way
var emailIDLabel= container.FindControl("emailIDLabel") as Label;
var senderRoleLabel = container.FindControl("SenderRoleLabel") as Label;
var messageLabel = container.FindControl("MessageLabel") as Label;
}
You can do something like the answer for this question.
But remember to validate the value (with int.TryParse(string) for example).
<asp:Button ID="ButtonDelete" runat="server" Text="Delete"
OnClick="ButtonDelete_Click"
UseSubmitBehavior="False"
CommandName="Deleterecord"
CommandArgument='<%# Eval("[SenderEmailID]") %>'/>
protected void ButtonDelete_Click(object sender, EventArgs e)
{
int id;
var button = (Button)sender;
if(!int.TryParse(button.CommandArgument, out id))
{
// log.Write("possible sql injection");
return;
}
// do what you want
}

Need Help in ASP.Net C# login page

What is wrong with this code? I have tried a lot of methods. But it always show login failed. No Build Errors though. I have a database named honeypot and a table called register in it,with username row and password row as varchars. I'm using built in login control. Can anyone help? I'm using Visual studio 2013.
home.aspx.cs
enter code here
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;
using System.Data.SqlClient;
namespace CodeInjection4
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
private static int count = 0;
protected void log1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (log1.UserName == "Admin" && log1.Password == "Admin")
{
Response.Redirect("Adminhome.aspx");
}
else if (YourValidationFunction(log1.UserName, log1.Password))
{
Session["User"] = log1.UserName;
e.Authenticated = true;
Response.Redirect("userhome.aspx");
log1.TitleText = "Successfully Logged In";
}
else
{
e.Authenticated = false;
count++;
if (count >= 3)
{
count = 0;
Session["User"] = log1.UserName;
Server.Transfer("MainPage.aspx");
}
}
}
private SqlConnection strConnection = new
SqlConnection("server=.\\SQLEXPRESS;database=honeypot;integrated security=true;");
private bool YourValidationFunction(string UserName, string Password)
{
bool boolReturnValue = false;
String SQLQuery = "SELECT UserName, Password FROM Register";
SqlCommand command = new SqlCommand(SQLQuery, strConnection);
SqlDataReader Dr;
try
{
strConnection.Open();
Dr = command.ExecuteReader();
while (Dr.Read())
{
if ((UserName == Dr["UserName"].ToString()) & (Password == Dr["Password"].ToString()))
{
boolReturnValue = true;
}
}
Dr.Close();
}
catch
{
}
return boolReturnValue;
}
protected void lnkRegis_Click(object sender, EventArgs e)
{
Response.Redirect("AdUserAcc.aspx");
}
}
}
Home.aspx
enter code here
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="CodeInjection4.Home" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script runat="server">
</script>
<style type="text/css">
#form1 {
text-align: center;
}
.auto-style1 {
width: 981px;
text-align: left;
}
.auto-style2 {
width: 961px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
Forestalling Code Injection</div>
<asp:Login ID="log1" OnAuthenticate="log1_Authenticate" runat="server" Width="1062px">
<LayoutTemplate>
<table cellpadding="1" cellspacing="0" style="border-collapse:collapse;">
<tr>
<td>
<table cellpadding="0">
<tr>
<td align="center" colspan="2">Log In</td>
</tr>
<tr>
<td align="right" class="auto-style2">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
</td>
<td class="auto-style1">
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="log1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" class="auto-style2">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
</td>
<td class="auto-style1">
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="log1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:CheckBox ID="RememberMe" runat="server" Text="Remember me next time." />
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color:Red;">
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
</td>
</tr>
<tr>
<td align="right" colspan="2" style="text-align: center">
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="log1" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:Login>
<br />
<asp:Button ID="Button1" runat="server" Text="Register" PostBackUrl="~/AdUserAcc.aspx" />
</form>
</body>
</html>
You are selecting all the users and looping through them. You have break out of the loop if you find a matching username and password such as
if ((UserName == Dr["UserName"].ToString()) & (Password == Dr["Password"].ToString()))
{
boolReturnValue = true;
break;
}
Othwerwise the next user will set it back to false.
A couple of notes:
Selecting all users and iterating through them is not scalable and wouldn't perform well. Instead you can pass in the username and password in WHERE clause. If you get a match then the login info is correct.
I'd recommend using logical-AND operator (&&) instead of bitwise-AND (&). Here's a SO thread with related discussion: Usage & versus &&
Consider using salted password hashes as opposed to plaintext passwords.

Retrieve data from database and show it in textboxes

I am currently working on a web application in which I have to fetch data from database and show it in text boxes. I have these fields:
Name,Comp_Name,User_Name,Email_Id,Password,User_Image,Category,Status
and on top of it I have 1 text box where user can enter the id to see the data. For example if I write 1 in the textbox. Then the text boxes will show me the data of the record with id=1 which is stored in database.
ASPX Code:
<head runat="server">
<title>Untitled Page</title>
<link href="User.css" type="text/css" rel="Stylesheet" />
<script type="text/javascript" src="imgpreview.js"></script>
<script type="text/javascript">
function showimagepreview(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#imgprvw').attr('src', e.target.result);
}
filerdr.readAsDataURL(input.files[0]);
}
}
</script>
<style type="text/css">
#Header
{
height: 65px;
}
.style1
{
height: 37px;
}
.style2
{
width: 217px;
height: 37px;
}
.style3
{
height: 37px;
width: 155px;
}
.style4
{
height: 129px;
width: 155px;
}
.style5
{
width: 217px;
height: 129px;
}
.style6
{
height: 129px;
}
</style>
<script>
window.onload=function()
{
document.getElementById("button").style.display='none';
}
function showButton(){
document.getElementById("button").style.display='block';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="Full">
<br />
<br />
<br />
<div id="Main">
<div id="MainHead">
<asp:Panel ID="Panel1" runat="server" Height="66px">
<br />
<asp:Label ID="ID" runat="server" Text="ID"></asp:Label>
& nbsp;
<input type="text" id="userText" value="Change the text" runat="server" /> <asp:Button
ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</asp:Panel>
</div>
<br />
<table style="height: 871px; width: 504px;">
<tr>
<td class="style3">
<asp:Label ID="Name" runat="server" Font-Bold="True" ForeColor="Black"
Text="Name :"></asp:Label>
</td>
<td class="style2">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="txtName"
Text="field required!"
runat="server" />
</td>
</tr><tr>
<td class="style3">
</td>
<td class="style2">
</td>
</tr>
<tr>
<td class="style3">
<asp:Label ID="CompName" runat="server" Font-Bold="True" ForeColor="Black"
Text="Comp Name :"></asp:Label>
</td>
<td class="style2">
<asp:TextBox ID="txtcomp" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style2">
</td>
</tr>
<tr>
<td class="style3">
<asp:Label ID="UserName" runat="server" Font-Bold="True" ForeColor="Black"
Text="User Name :"></asp:Label>
</td>
<td class="style2">
<asp:TextBox ID="txtuser" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
ControlToValidate="txtUser"
Text="field required!"
runat="server" />
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style2">
</td>
</tr>
<tr>
<td class="style3">
<asp:Label ID="Password" runat="server" Font-Bold="True" ForeColor="Black"
Text="Email-ID :"></asp:Label>
</td>
<td class="style2">
<asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3"
ControlToValidate="txtemail"
Text="field required!"
runat="server" />
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style2">
</td>
</tr>
<tr>
<td class="style3">
<asp:Label ID="Label5" runat="server" Font-Bold="True" ForeColor="Black"
Text="Password :"></asp:Label>
</td>
<td class="style2">
<asp:TextBox ID="txtpass" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style2">
</td>
</tr>
<tr>
<td class="style4">
<asp:Label ID="Label6" runat="server" Font-Bold="True" ForeColor="Maroon"
Text="User Image :"></asp:Label>
</td>
<td class="style5">
<input type="file" name="filUpload" id="filUpload" onchange="showimagepreview(this)" runat="server"/>
</td>
<td class="style6">
<asp:Panel ID="Panel2" runat="server" Height="122px">
<img id="imgprvw" alt="uploaded image preview"/>
</asp:Panel>
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style2">
</td>
</tr>
<tr>
<td class="style3">
<asp:Label ID="Label7" runat="server" Font-Bold="True" ForeColor="Black"
Text="Category :"></asp:Label>
</td>
<td class="style2">
<asp:TextBox ID="txtcat" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style2">
</td>
</tr>
<tr>
<td class="style3">
<asp:Label ID="Label8" runat="server" Font-Bold="True" ForeColor="Black"
Text="Status :"></asp:Label>
</td>
<td class="style2">
<asp:DropDownList ID="txtddl" runat="server" Height="28px" Width="151px"
AutoPostBack="True">
<asp:ListItem>Store Manager</asp:ListItem>
<asp:ListItem>Pro Manager</asp:ListItem>
<asp:ListItem>Engg</asp:ListItem>
<asp:ListItem>Admin</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style2">
</td>
</tr>
<tr>
<td class="style3">
<asp:Label ID="Label9" runat="server" Font-Bold="True" ForeColor="Black"
Text="Category No :"></asp:Label>
</td>
<td class="style2">
<asp:TextBox ID="txtcatno" runat="server" Height="21px" Width="151px"> </asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style2">
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style2">
</td>
</tr>
<tr>
<td class="style1" colspan="2">
& nbsp; &n bsp;
<asp:Button id="Submit" runat="server" Text="Submit" onclick="Submit_Click" />
<input type="button" id="btnupd" value="New Button" runat="server" onclick="return btnupd_onclick()" />
</td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
C# Code:
using System;
using System.Configuration;
using System.Data;
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 MySql.Data.MySqlClient;
using System.Windows.Forms;
public partial class _Default : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection("DataSource=localhost;database=mrp;userid=**;password=**;port=**");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
try
{
//This is my connection string i have assigned the database file address path
string MyConnection2 = "datasource=localhost;port=**;username=**;password=**;database=mrp";
//This is my insert query in which i am taking input from the user through windows forms
string Query = "insert into user_tbl(Name,Comp_Name,User_Name,Email_Id,Password,User_Image,Category,Status) values('" + this.txtName.Text + "','" + this.txtcomp.Text + "','" + this.txtuser.Text + "','" + this.txtemail.Text + "','" + this.txtpass.Text + "','" + this.filUpload.Value + "','" + this.txtcat.Text + "','" + this.txtddl.Text + "');";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader(); // Here our query will be executed and data saved into the database.
MessageBox.Show("Save Data");
while (MyReader2.Read())
{
}
MyConn2.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
MySqlConnection con1 = new MySqlConnection("Data Source=localhost;database=mrp;userid=**;password=**;port=**");
var str = "select * from user_tbl,con1";
DataTable dt = new DataTable();
con1.Open();
MySqlDataReader myReader = null;
MySqlCommand myCommand = new MySqlCommand("Select * from user_tbl where Id=" + Id1, con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtName.Text = (myReader["Name"].ToString());
txtemail.Text = (myReader["Email_Id"].ToString());
txtddl.Text = (myReader["Status"].ToString());
txtpass.Text = (myReader["Password"].ToString());
txtcomp.Text = (myReader["Comp_Name"].ToString());
txtuser.Text = (myReader["User_Name"].ToString());
filUpload.Value = (myReader["User_Image"].ToString());
//and whatever you have to retrieve
}
con1.Close();
}
}
Use this code snippet:
SqlConnection con1 = new SqlConnection("your connection string");
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("your query", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtName.Text = (myReader["name"].ToString());
txtEmail.Text = (myReader["email"].ToString());
//and whatever you have to retrieve
}
con1.Close();

Show text entered from textbox in a label asp net

so I have this code in asp .net
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 248px;
}
.auto-style2 {
width: 253px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<table style="width:100%;">
<tr>
<td class="auto-style2">
</td>
<td>
<asp:SqlDataSource ID="Artikujt" runat="server" ConnectionString="<%$ ConnectionStrings:ChipString %>" SelectCommand="SELECT * FROM [Artikujt]"></asp:SqlDataSource>
</td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" ></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder3" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder4" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder5" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td>
<td> </td>
</tr>
</table>
<br />
</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;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
AddItems();
}
}
DropDownList artikulli;
TextBox cmimi;
Label tregoCmimi;
TextBox sasia;
Label cmimiGjithsej;
protected void AddItems()
{
if (!string.IsNullOrEmpty(TextBox1.Text))
{
int a = int.Parse(TextBox1.Text);
for (int j = 1; j <= a; j++)
{
artikulli = new DropDownList();
cmimi = new TextBox();
tregoCmimi = new Label();
sasia = new TextBox();
cmimiGjithsej = new Label();
//artikulli.ID = j.ToString(IDUnik.ToString("N").Substring(31));
artikulli.ID = "artikulli_" + j.ToString();
artikulli.AutoPostBack = true;
cmimi.ID = "cmimi_" + j.ToString();
cmimi.AutoPostBack = true;
tregoCmimi.ID = "tregoCmimi_" + j.ToString();
sasia.ID = "sasia_" + j.ToString();
sasia.AutoPostBack = true;
cmimiGjithsej.ID = "cmimiGjithsej_" + j.ToString();
PlaceHolder1.Controls.Add(artikulli);
PlaceHolder2.Controls.Add(cmimi);
PlaceHolder3.Controls.Add(tregoCmimi);
PlaceHolder4.Controls.Add(sasia);
PlaceHolder5.Controls.Add(cmimiGjithsej);
DataTable listaArtikujt = new DataTable();
using (SqlConnection lidhje = new SqlConnection(ConfigurationManager.ConnectionStrings["ChipString"].ConnectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Artikulli] FROM [Artikujt]", lidhje);
adapter.Fill(listaArtikujt);
artikulli.DataSource = listaArtikujt;
artikulli.DataTextField = "Artikulli";
artikulli.DataBind();
}
catch (Exception ex)
{
Response.Write("Gabim:" + ex.ToString());
}
}
}
}
}
}
What I want to do is, after PostBack, after I have added number 2 it will show 2 DropDownlist, 2 Textboxes, 2 Labels, 2 Textboxes again and 2 other Labels.
I am trying to do after Post back, after I enter a number in TextBox cmimi = new TextBox(); it will automatically be added in the label below. I am trying to do but no luck.
I hope you understood my explanation.
Thank you. :)

Why DropDownList value is missing during postback?

I have a DropDownList whose value is missing when I trigger post-back. Here my aspx, JavaScript and C# code.
Javascript:
<script type="text/javascript">
function stfocus(event) {
if (event.keyCode == 13) {
document.getElementById('tbfrompalletno').focus();
}
}
function tblocenter(event) {
if (event.keyCode == 13) {
__doPostBack('__Page', 'save');
}
}
</script>
ASPX:
<table>
<tr>
<td colspan="2" style="text-anchor: middle; text-align: center; border: thin solid #000000; background-color: #CCCCCC;">
<asp:Label ID="lblheader" runat="server" Text="Partial Pallet Transfer"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: left">
<asp:Label ID="Label_ErrorMsg" runat="server" Text="" BackColor="Red" ForeColor="White" />
<asp:Label ID="Label_Info" runat="server" Text="" BackColor="Green" ForeColor="White" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblwhscode" runat="server" Text="WHS Code:"></asp:Label>
</td>
<td>
<asp:DropDownList ID="cbwhscode" runat="server"
DataSourceID="sql_whs_code" DataTextField="whs_name" DataValueField="whs_code">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblfromloc" runat="server" Text="From Location:"></asp:Label>
</td>
<td>
<asp:TextBox ID="tbfromloc" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblfrompalletno" runat="server" Text="From Pallet:"></asp:Label>
</td>
<td>
<asp:TextBox ID="tbfrompalletno" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClick="btnsubmit_Click" UseSubmitBehavior="false" />
<asp:Button ID="btnback" runat="server" Text="Back" OnClick="btnback_Click" UseSubmitBehavior="false" />
<asp:Button ID="btnhome" runat="server" Text="Home" OnClick="btnhome_Click" UseSubmitBehavior="false" />
</td>
</tr>
</table>
<asp:SqlDataSource ID="sql_whs_code" runat="server" ConnectionString="<%$ ConnectionStrings:infologConnection %>"
SelectCommand="sp_select_auth_whs_code" SelectCommandType="StoredProcedure" OnSelecting="sql_whs_code_Selecting">
<SelectParameters>
<asp:Parameter Name="group_id" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
C# :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.tbfromloc.Attributes.Add("onkeydown", "javascript:stfocus(event);");
this.tbfrompalletno.Attributes.Add("onkeydown", "javascript:tblocenter(event);");
ViewState["language"] = (string)Session["language"];
ViewState["group_id"] = (string)Session["group_id"];
this.loadsetting();
this.cbwhscode.DataBind();
if (this.cbwhscode.Items.Count > 0)
{
ListItem Check = this.cbwhscode.Items.FindByValue(Session["default_whs_code"].ToString());
if ((Check != null) && this.cbwhscode.Items.Contains(Check))
{
this.cbwhscode.SelectedValue = Session["default_whs_code"].ToString();
}
}
this.tbfromloc.Focus();
}
string parameter = Request["__EVENTARGUMENT"];
if (parameter = "save" ) this.btnsubmit_Click(sender, e);
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
this.Label_ErrorMsg.Text = "";
this.Label_Info.Text = "";
string i_whs_code = this.cbwhscode.SelectedValue;
string i_pack_id = this.tbfrompalletno.Text;
string i_loc_code = this.tbfromloc.Text;
Tuple<bool, int, string> result = RF03BLL_Transfer.rf_partial_transfer_check_loc_pallet(i_whs_code, i_pack_id, i_loc_code);
bool o_succeed = result.Item1;
int o_msg_num = result.Item2;
string o_add_info = result.Item3;
if (o_succeed)
{
string strPost = "whscode=" + HttpUtility.UrlEncode(i_whs_code) +
"&palletno=" + HttpUtility.UrlEncode(i_pack_id) +
"&loccode=" + HttpUtility.UrlEncode(i_loc_code);
string path = "~/RF03F_Transfer/RF030202F_TransferPartialAddPacking.aspx?";
path += strPost;
Response.Redirect(path);
}
else
{
this.Label_ErrorMsg.Text = Module.getMsg(o_msg_num, ViewState["language"].ToString());
}
}
protected void sql_whs_code_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.Parameters["#group_id"].Value = ViewState["group_id"].ToString();
}
My issue is: why value of DropDownList is missed?

Categories