Cannot acces variables from aspx to cs - asp.net

I have a problem. I have created asp.net web page in c#. I created it using the default master page that visuals studio gives you. There in register.aspx there is a textbox for username like tihs:
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
<asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName"
CssClass="failureNotification" ErrorMessage="User Name is required." ToolTip="User Name is required."
ValidationGroup="RegisterUserValidationGroup">*</asp:RequiredFieldValidator>
In cs folder, under the button i put a code that put the registered user into database, but it cannot find the variable of text box. What is the problem here?
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
//FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false
//string continueUrl = RegisterUser.ContinueDestinationPageUrl;
//if (String.IsNullOrEmpty(continueUrl))
//{
// continueUrl = "~/";
//}
//Response.Redirect(continueUrl);
try
{
SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
DataTable objdatatable = new DataTable();
string validationquery = "select * from Uporabniki where username=`" + UserName.Text + "`";
SqlDataAdapter objdavalidate = new SqlDataAdapter(validationquery, objcon);
objdavalidate.SelectCommand.CommandType = CommandType.Text;
objdavalidate.Fill(objdatatable);
if (objdatatable.Rows.Count > 0)
{
...

Related

DropDownList SelectIndexChanged not working?

This seems to be a common problem. I have tried different solutions but its still not working. This is my code.
HTML:
<div class="form-group">
<label for="exampleInputEmail1">Artist *</label>
<asp:DropDownList ID="artistDropdown" runat="server" CssClass="form-control" AutoPostBack="True" OnSelectedIndexChanged="artistDropdown_SelectedIndexChanged" ViewStateMode="Enabled"></asp:DropDownList>
<asp:TextBox ID="mytest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="artistDropdown" SetFocusOnError="true" ErrorMessage="Required Field" Font-Bold="True" Font-Names="Arial" Font-Size="X-Small" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:Label ID="lblMessage" runat="server" CssClass="help-block" Visible="False">Cant select Artist with no Manager</asp:Label>
</div>
Function: OnSelectedIndexChanged
protected void artistDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedArtist = artistDropdown.SelectedValue;
mytest.Text = selectedArtist;
string query = "Select [Manager ID] from Artist Where ID = '" + selectedArtist + "'";
string myConnection = dbController.connectionString;
SqlConnection conn = new SqlConnection(myConnection);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
object obj = cmd.ExecuteScalar();
if (obj is System.DBNull)
{
artistDropdown.SelectedValue = "";
lblMessage.Visible = true;
}
else
{
lblMessage.Visible = false;
}
conn.Close();
}
I am loading DropDownList in Page_Load() function and AutoPostBack="True" is set for DropDownList.
I have also made a TextBox which is being set to the selectedValue from DropDownList to check if on OnSelectedIndexChanged is firing. But text box remains empty.
What am I doing wrong?
Did you put the binding of your dropdown in the if (!postback) {} ?
If you rebind the list after every postback, you get the value of the first list item when you reach the artistDropdown_SelectedIndexChanged event.
If this item has an empty string value...

Textinfo Not posting to .mdb file. Not sure why

I am currently stumped on a particular issue which I need your help. I'm having this particular issue with my asp.net website.
For whatever reason when a user is trying to save information from a text box to my .mdb file it's not accepting it. Everything compiles fine and I have quadruple checked all of the ID and string names and everything appears to match with what it should on the table in the .mdb, the .c file, and the aspx.cs pages.
Here is the .aspx page that the information is input on
<asp:Label ID="lblFirstName1" runat="server" align="left" Text="First Name: " Width="125px"></asp:Label>
<asp:TextBox ID="txtfirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtfirstName" ErrorMessage="First Name cannot be empty"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblLastName1" runat="server" Text="Last Name: " Width="125px"></asp:Label>
<asp:TextBox ID="txtlastName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtlastName" ErrorMessage="Last Name cannot be empty"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblUserAddress1" runat="server" Text="Street Addres: " Width="125px"></asp:Label>
<asp:TextBox ID="txtstreetAddress" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txtstreetAddress"
ErrorMessage="Address cannot be empty"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblcity1" runat="server" Text="City: " Width="125px"></asp:Label>
<asp:TextBox ID="txtcity" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="txtcity"
ErrorMessage="City cannot be empty"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblstate1" runat="server" Text="State: " Width="125px"></asp:Label>
<asp:TextBox ID="txtstate" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="txtstate"
ErrorMessage="State cannot be empty"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblzipCode1" runat="server" Text="Zip Code: " Width="125px"></asp:Label>
<asp:TextBox ID="txtzipCode" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ControlToValidate="txtzipCode"
ErrorMessage="Zip Code cannot be empty"></asp:RequiredFieldValidator>
here is the info from the .cs page that it is using to save to the .mdb
public static bool Saveneworder(string Database, string firstName, string lastName, string streetAddress, string city, string state, string zipCode )
{
bool recordSaved;
// Create a new Oledb Transaction object
OleDbTransaction myTransaction = null;
try
{
// Create a New Connection Object to the Access Database
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
// set the transaction object and start the transaction
myTransaction = conn.BeginTransaction();
command.Transaction = myTransaction;
strSQL = "Insert into tblOrder " +
"(firstName, lastName, streetAddress, city, state, zipCode) values ('" +
firstName + "', '" + lastName + "', '" + streetAddress + "', '" + city + "', '" + state +
"', '" + zipCode + "')";
// set the command text of the command object
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Execute the insert statement
command.ExecuteNonQuery();
myTransaction.Commit();
// Close the Database connection
conn.Close();
recordSaved = true;
}
catch (Exception ex)
{
//Rollback the transaction if some failure occurs
myTransaction.Rollback();
recordSaved = false;
}
return recordSaved;
}
Here is the first aspx.cs files that transfers the data from the textboxes to the orderverified page that lists the else statement that the information did not post
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (ValidateFields()) //if Validate fields method has returned true
{
Session.Add("txtfirstName", txtfirstName.Text);
Session.Add("txtlastName", txtlastName.Text);
Session.Add("txtstreetAddress", txtstreetAddress.Text);
Session.Add("txtcity", txtcity.Text);
Session.Add("txtstate", txtstate.Text);
Session.Add("txtzipCode", txtzipCode.Text);
Server.Transfer("orderverified.aspx");
}
and it forwards the information to this aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
//So here we are initializing text property of the textbox "txtVerifiedInfo" after fetching the
//values from the session object
txtVerifiedInfo.Text = Session["txtfirstName"].ToString() +
"\n" + Session["txtlastName"].ToString() +
"\n" + Session["txtstreetAddress"].ToString() +
"\n" + Session["txtcity"].ToString() +
"\n" + Session["txtstate"].ToString() +
"\n" + Session["txtzipCode"].ToString()
;
// Check if the record is successfully saved in the tblOrder Table and prints the appropriate message in the text box txtVerifiedInfo
if (clsDataLayer.Saveneworder(Server.MapPath("App_Data\\WSC_DB.mdb" ),
Session["txtfirstName"].ToString(),
Session["txtlastName"].ToString(),
Session["txtstreetAddress"].ToString(),
Session["txtcity"].ToString(),
Session["txtstate"].ToString(),
Session["txtzipCode"].ToString() ))
{
txtVerifiedInfo.Text = txtVerifiedInfo.Text +
"\nThe Order successfully submitted!";
}
else
{
txtVerifiedInfo.Text = txtVerifiedInfo.Text +
"\n The order did not save, please return to the previous screen and verify all of your data is correct, thank you.";
}
On the last page - Orderverified.aspx i have a multiline text box that clearly shows all of the data but it is returning my else statement that it was not able to save to the tblOrder
sorry for posting so much code but I really am stumped on why this isn't saving.
Thank you for reading and for your time
Upon further troubleshooting i have tried excluding everything EXCEPT for the firstName and it still will not post.
i feel the problem is most likely with the .cs files code that is the sql statement to insert into the tblOrder
I've never used OleDbConnection, but it seems you may need to use .Parameters.AddWithValue().
See this StackOverflow answer.
Okay, I figured it out - I couldnt find an issue with any of the code because there wasnt one!!
I turns out i had the primary key int he .mdb set as a field that i was not inputting to and it was causing it not to save because it was set to text instead of autonumber and would not let the file save!! thank you for taking a look at it jeremywho

Take parameter from listview

i have this code:
protected void Button1_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(GetConnectionString());
{
System.Data.SqlClient.SqlCommand cmd;
sc.Open();
cmd = new System.Data.SqlClient.SqlCommand("SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;", sc);
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#ID", System.Data.SqlDbType.Text)).Value = (TextBox)ListView1.FindControl("box1");
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
I need take value ID from listview, but with this code I have this error:
...expects the parameter '#ID', which was not supplied....
This part of my listview...
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID_zapas" DataSourceID="SqlDataSource1" style="text-align: center ">
<AlternatingItemTemplate>
<tr style="background-color: #e9ffe9;color: #284775;text-align:center">
<td>
<asp:TextBox ID="box1" runat="server" Text='<%# Eval("ID_zapas") %>' Visible="false" />
...
<td style="width:50px;background-color:white">
<asp:LinkButton ID="Button1" runat="server" OnClick="Button1_Click" Visible='<%# HttpContext.Current.User.IsInRole("admin") %>' CausesValidation="False" OnClientClick="javascript: return confirm('Opravdu chcete zápas zkopírovat?');">
<asp:Image ID="Image2" runat="server" ImageUrl="~/Icons/copy.png" Width="29px" Height="29px" ToolTip="Zkopírovat zápas" />
</asp:LinkButton>
</td>
</tr>
</AlternatingItemTemplate>
Have you some idea?
As per comments, please try this:
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
var box1 = (TextBox)((LinkButton)sender).Parent.FindControl("box1");
using (var sc = new SqlConnection(GetConnectionString()))
{
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;";
cmd.Parameters.AddWithValue("#ID", box1.Text);
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
}
When using data-aware controls such as a ListView here, the controls are created with automatic unique IDs per data item. This means that you can have more than 1 of the same control (such as "box1" in this case) within the page that should be referenced by the data item (((LinkButton)sender).Parent which is ListViewDataItem, representing the row).
ListViewDataItem.FindControl will find controls of a specific server ID within its own child scope, allowing you to get values for controls within the same row of the button that is being clicked.

Formview not letting me add a second record after adding a first

I have a FormView which allows inserting of records into a table, and then also sends out a confirmation email that a record has been added. The email is supposed to go a particular set of users, based on a department selected. So I have the below. All works well, except after I add a record, and the email sends, and then it takes me back, and when I click the Add new record button again I get 'Could not find control 'formViewNewItem$ddlInsertDepartment' in ControlParameter 'RoleID'.' It's like the formView is staying in insertmode or something after a record is inserted into the table.
Data source for emails to be sent:
<asp:SqlDataSource ID="dsourceToEmails" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT [Email] + ',' FROM [Users] WHERE [Role] = #RoleID FOR XML PATH ('')">
</asp:SqlDataSource>
FormView code:
<asp:FormView ID="formViewNewItem" runat="server" DataKeyNames="Test_ID"
DataSourceID="testDataSource" OnDataBound="formViewNewItem_DataBound"
OnItemInserted="testRecord_Inserted">
<InsertItemTemplate>
<asp:DropDownList ID="ddlInsertDepartment" runat="server" ClientIDMode="Static">
<asp:ListItem></asp:ListItem>
<asp:ListItem>Accounting</asp:ListItem>
<asp:ListItem>Marketing</asp:ListItem>
<asp:ListItem>Programming</asp:ListItem>
</asp:DropDownList>
</InsertItemTemplate>
<ItemTemplate>
<asp:Button ID="btnAddNewRecord" runat="server" CausesValidation="False"
CommandName="New" Font-Bold="True" Text="Add New"
onclick="btnAddNewRecord_Click" />
</ItemTemplate>
</asp:FormView>
Page Load (only create parameter for email if in insert mode)
protected void Page_Load(object sender, EventArgs e)
{
if (formViewNewItem.CurrentMode == FormViewMode.Insert)
{
// Create your ControlParameter
ControlParameter deptParam = new ControlParameter();
deptParam.ControlID = formViewNewItem.FindControl("ddlInsertDepartment").UniqueID;
deptParam.PropertyName = "SelectedValue";
deptParam.Name = "RoleID";
deptParam.Type = TypeCode.String;
// Add it to your SelectParameters collection
dsourceToEmails.SelectParameters.Add(deptParam);
}
OnInserted, once record is successfully added, send email:
protected void testRecord_Inserted(object sender, EventArgs e)
{
DataView dvToEmails = (DataView)dsourceToEmails.Select(DataSourceSelectArguments.Empty);
string emailsTo = (string)dvToEmails.Table.Rows[0][0];
emailsTo = emailsTo.TrimEnd(',');
string networkUserName = Page.User.Identity.Name;
string emailUserName = networkUserName.Substring(12);
DropDownList departmentSelection = (DropDownList)formViewNewItem.FindControl("ddlInsertDepartment");
var message = new MailMessage();
var client = new SmtpClient();
message.From = new MailAddress("test#abc.com", "Task Tracker");
message.To.Add(emailsTo);
message.Subject = "New Project assigned for " + departmentSelection.SelectedValue;
message.Body = "A new task has been assigned.
<br /><br /><b>Entered by:</b> " + emailUserName;
message.IsBodyHtml = true;
client.Send(message);
}
Got the answer to this...I had to move the SqlDataSource to the InsertItemTemplate, and then use the FindControl method in the OnInserted code to find the SqlDataSource that I had moved, but all worked as it should after all of that.

Repeater displaying only first record with CSS

In the below code by using DIV tag repeater is displaying only first one record retrieved from database. By removing DIV tag mbody everything is working fine. But to align the format of the script I started to use this DIV tag but I am unable to view add records. Please check where the error is at.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick" Interval="1000" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger controlid="Timer1" eventname="Tick" />
</Triggers>
<ContentTemplate>
<asp:Repeater ID="Shout_Box" runat="server">
<ItemTemplate><div id="mbody">
<%# DataBinder.Eval(Container.DataItem, "Message") %>
</div> </ItemTemplate>
</asp:Repeater><div id="sbox_button">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /></div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" UpdateMode="Conditional" runat="server">
<ContentTemplate><div id="sb_text"><asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Wrap="true" Width="400" Height="60" /></div></ContentTemplate>
</asp:UpdatePanel>
In the above code 1 repeater, 1 button and 1 textbox are used. By adding text to the textbox and clicking button the textbox's value goes to database and retrieved by using timer. This script is a kind of chat script. But using DIV tag I am unable to display all records :-(
Server side code
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Timer1_Tick(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=chatserver;" + "UID=root;" + "PASSWORD=*****;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
try
{
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("Select message from shoutbox", MyConnection);
OdbcDataReader dr = cmd.ExecuteReader();
ArrayList values = new ArrayList();
while (dr.Read())
{
string ep = dr[0].ToString();
values.Add(new PositionData(ep));
Shout_Box.DataSource = values;
Shout_Box.DataBind();
}
TextBox1.Text = "";
}
catch
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=chatserver;" + "UID=root;" + "PASSWORD=*****;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
OdbcCommand cmd = new OdbcCommand("INSERT INTO shoutbox(name, message)VALUES(?, ?)", MyConnection);
cmd.Parameters.Add("#email", OdbcType.VarChar, 255).Value = "tick";
cmd.Parameters.Add("#email", OdbcType.Text).Value = TextBox1.Text;
MyConnection.Open();
cmd.ExecuteNonQuery();
MyConnection.Close();
TextBox1.Text = string.Empty;
UpdatePanel2.Update();
}
Move the databinding out of the while loop:
while (dr.Read())
{
string ep = dr[0].ToString();
values.Add(new PositionData(ep));
}
Shout_Box.DataSource = values;
Shout_Box.DataBind();
It does not make any sense to bind the data after reading every value.

Resources