Textinfo Not posting to .mdb file. Not sure why - asp.net

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

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...

c# asp.net displaying image in gridview

I wish to display an image in a gridview.
I have a database with 4 columns - id, author, comment, filename (which holds the img path)
http://postimg.org/image/4loz8t9fb/
I have an image upload method so when the user writes his comment, chooses a photo and clicks submit- his name, the comment and the photo path goes to the database (and the photo itself is uploaded to 'Images' folder in the project folder).
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns = "False"
Font-Names = "Arial" Height="375px" Width="498px" DataSourceID="SqlDataSource2" >
<Columns>
<asp:BoundField DataField="Author" HeaderText="Author" SortExpression="Author" />
<asp:BoundField DataField="Comment" HeaderText="Comment" SortExpression="Comment" />
<asp:BoundField DataField="FileName" HeaderText="FileName" SortExpression="FileName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate >
<asp:Image ID="Image1" runat="server" ImageUrl ='<%# Eval("FileName") %>' height="120px" Width="150px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is the c# code-
protected void addcomment_Click(object sender, EventArgs e)
{
string FileName = "";
if (fileupload.PostedFile != null)
{
FileName = Path.GetFileName(fileupload.PostedFile.FileName);
//Save files to disk
fileupload.SaveAs(Server.MapPath("Images/" + FileName));
}
if (TextBox1.Text.Length > 0)
{
string name = firstName + " " + lastName;
SqlCommand cmd = new SqlCommand("insert into comments values(#name,#comment,#filename)", conn);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#comment", TextBox1.Text);
cmd.Parameters.AddWithValue("#filename", Server.MapPath("Images/" + FileName));
conn.Open();
cmd.ExecuteNonQuery();
GridView1.DataBind();
conn.Close();
TextBox1.Text = "";
Response.Redirect(Request.Url.AbsoluteUri);
}
else
{
TextBox1.Text = "You have to type something buddy!";
}
}
The gridview datasource is the sql of course.
Here is an image of the database and the website
http://postimg.org/image/4loz8t9fb/
ImageUrl ='<%# "Images\\"+Eval("FileName") %>'
try this way...
Dont set full path ,
string savepath = "~/Images/" + Filename;
cmd.Parameters.AddWithValue("#filename", savepath));
just change this line it will work
and even change
fileupload.SaveAs(Server.MapPath("~/Images/" + FileName));
in your design view click on smart tag of your gridview and select 'Edit Columns...' then in the opened window create an ImageField and in it's properties on right side of window, under 'Data' pane set the property 'DataImageUrlField' to the field that contains your urls that in this case is 'FileName'. it should works.

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.

Cannot acces variables from aspx to cs

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)
{
...

DataGrid and MultiBind

I'm new to ASP.NET and are struggling with displaying data in a GridView. I got most of it working with help from this forum. Currently I'm trying to build a file name from an ID and a "file extension" from a database, but got stuck. I guess I need to use MultiBind to get this working? My file name is ID + "_tn" + file extension, and this is my code.
<asp:GridView ID="HitGridView" runat="server" onrowdatabound="HitsRowBid">
<Columns>
<asp:TemplateField HeaderText="Street">
<ItemTemplate>
<asp:TextBox ID="Adress" runat="server" width="200" Text='<%# Bind("StreetName") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:ImageButton ID="defaultImg" runat="server" ImageUrl='<%# Bind("ImgId") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in code behind
protected void HitsRowBid(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton imgBtn = (ImageButton)e.Row.FindControl("defaultImg");
imgBtn.ImageUrl = "Content/FileUpload/" + imgBtn.ImageUrl + "_tn" + ".jpg";
}
}
But how do I get the file extension that is stored in the database?
I mainly use ListViews, but there are a couple of ways to accomplish this. One way would be to use DataKeys when databinding and retrieve the value by using the row index in the onrowdatabound event. Another option would be to write a helper method in codebehind and call it during databinding, something like:
protected string FormatImagePath(string fileName)
{
string imagePath = Request.ApplicationPath.TrimEnd('/') + "/previews/" + fileName;
FileInfo testFile = new FileInfo(Helpers.BaseSiteFilePath + #"previews\\" + fileName);
if (!testFile.Exists)
{
imagePath = Request.ApplicationPath.TrimEnd('/') + "/images/no_preview.png";
}
return imagePath;
}
Calling it like such:
ImageUrl='<%# FormatImagePath(Eval("PreviewURL").ToString()) %>'

Resources