I have a SQL database with 1 table with 3 columns.. documentID, documentTitle, documentBody.
I have an aspx page with 2 inputs... 1 for title 1 for body and 1 submit button.
How on earth do I just get the text inside the input fields to store in a new row in the database? I cannot find a simple... concrete answer and there is no way that it is that complicated.
<form id="form1" runat="server">
<div style="width: 800px; margin-top: 40px;">
<p style="text-align: left">
Title</p>
<p>
<input id="inputTitle" runat="server" type="text" style="width: 100%; padding: 6px;
font-size: large" /></p>
<p style="text-align: left">
Body</p>
<p>
<textarea id="inputBody" runat="server" style="width: 100%; height: 400px" cols="22"
rows="66"></textarea></p>
<p>
<input id="save" type="submit" onclick="submit_onclick" value="Save as the newest version" /><span> or
</span><a href>Cancel</a></p>
</div>
</form>
The simplest would be to use straight ADO.NET in the OnClick handler - but that leads to spaghetti code and intermingling of UI manipulation (setting and reading e.g. textboxes) and data access code - which is not a good approach.
Anywhere - here goes the simplest approach (again: not recommended for real use)
protected void submit_onclick(object sender, EventArgs e)
{
string sqlStmt = "INSERT INTO dbo.YourTable(documentTitle, documentBody) " +
"VALUES(#docTitle, #docBody)";
string connectionString = WebConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
cmd.Parameters.Add("#docTitle", SqlDbType.VarChar, 100).Value = tbxTitle.Text.Trim();
cmd.Parameters.Add("#docBody", SqlDbType.VarChar, 100).Value = tbxBody.Text.Trim();
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
Of course - using an ORM might make things easier from a programming perspective (just "new up" a Document, set its .Title and .Body properties, and call .Save() on it - or something like that) - but these ORM's do have a certain learning curve, too.
Also: if you're looking at doing simple to medium-complexity stuff or if you're just getting into ASP.NET development - why not check out Microsoft WebMatrix? It contains a lot of helpers and "wrappers" that make dealing with typical tasks much easier - especially the database, for one!
See part 5 of the intro tutorial on database development.
Use ASP.NET server controls for your inputs, instead of an <input>.
<asp:Button runat="server" Text="Submit" id="sub" OnClick="SaveDetails" />
<asp:TextBox runat="server" id="txtBody" />
<asp:TextBox runat="server" id="txtTitle" />
Try something like this in your code-behind:
protected void SaveDetails(object sender, EventArgs e) {
using (var conn = new SqlConnection("Data Source=YourServerName;Initial Catalog=YourDatabaseName;Integrated Security=True;"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = #"INSERT INTO docs (documentTitle, documentBody)
VALUES (#title,#body);";
cmd.Parameters.AddWithValue("#title", txtTitle.Text.Trim());
cmd.Parameters.AddWithValue("#body", txtBody.Text.Trim());
cmd.ExecuteNonQuery();
}
}
Related
I'm fairly new to asp.net and c#, i've connected to a SQL database and now i'd like to show the data i have into a table.
This is my back-end:
public string getWhileLoopData()
{
string htmlStr = "";
SqlConnection conn = new SqlConnection("Data Source = secret;Initial Catalog = GTI;Persist Security Info = True;Integrated Security = true;User ID = user;Password = pass;");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [CORE_SYS_STATUS]", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int ID = reader.GetInt32(0);
int SYSTEM_NAME = reader.GetInt32(0);
int SYSTEM_STATUS = reader.GetInt32(0);
int SYSTEM_SHORTMSG = reader.GetInt32(0);
htmlStr += "<tr><td>" + ID + "<tr><td>" + SYSTEM_NAME + "<tr><td>" + SYSTEM_STATUS + "<tr><td>" + SYSTEM_SHORTMSG;
}
conn.Close();
return htmlStr;
}
This is my front-end:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="ContentPlaceHolder">
<div class="bg-light text-center bg-light rounded border border-dark m-4">
<div class="col-md-12">
<h1 class="display-4 text-center p-4">Gestão de Alertas</h1>
<table class="table table-bordered table-hover text-center p-4 border border-dark">
<thead>
<tr class="table-success disabled">
<th style="width: 5%" scope="col">ID</th>
<th style="width: 20%" scope="col">Nome</th>
<th style="width: 15%" scope="col">Status</th>
<th style="width: 45%" scope="col">Mensagem</th>
</tr>
</thead>
<tbody>
<!-- I want to insert data here -->
</tbody>
</table>
</div>
</div>
</asp:Content>
And this is the result:
Result
It may look really silly and easy but i'm very new to this of programming, if anyone could help me figure out how to insert my data into the table i'd be very glad. Thank you!
There are many ways to achieve this.
I would recommend to take a look in the docs regarding to DataBinding, e.g.:
Retrieving data in aspnet web-forms
GridView DataBind (look at the sample there)
Furthermore you should take a look at the documentation regarding GetInt32:
GetInt32 MSDN
The parameter is the index of the column in the select statement and you are always passing 0 and that is certainly not what you want. I'd also recommend to explicitly name the columns you want in the select statement instead of using select *.
For a quick solution you could replace <%=getWhileLoopData()%> with an <asp:Literal /> control; in your code-behind, set it's Text property to (getWhileLoopData).
If you're new to ASP.NET, learning WebForms data binding will take a while as it's got some rules and peculiarities you need to get to grips with. To be honest unless you have to build this thing in WebForms you should start learning ASP.NET MVC, WebForms is a dead technology.
<% HtmlString str = new HtmlString(getWhileLoopData()); %>
<%= str %>
Here's the template's HTML form :
<form class="form-login" action="index.html">
<h2 class="form-login-heading">sign in now</h2>
<div class="login-wrap">
<input type="text" class="form-control" placeholder="User ID" autofocus="autofocus">
<br>
<input type="password" class="form-control" placeholder="Password">
<label class="checkbox">
<span class="pull-right">
<a data-toggle="modal" href="login.html#myModal"> Forgot Password?</a>
</span>
</label>
<button class="btn btn-theme btn-block" href="index.html" type="submit"><i class="fa fa-lock"></i> SIGN IN</button>
Here's my modification to it :
<form id="form1" runat="server" class="form-login" method="post" action="HomeDoc.aspx">
<div>
<h2 class="form-login-heading">sign in now</h2>
<div class="login-wrap">
<input type="text" class="form-control" placeholder="User ID" id="userid" runat="server" autofocus="autofocus"/>
<br/>
<input type="password" class="form-control" placeholder="Password" id="password" runat="server" />
<label class="checkbox">
<span class="pull-right">
<a data-toggle="modal" href="StaffLogin.aspx#myModal"> Forgot Password?</a>
</span>
</label>
<button class="btn btn-theme btn-block" runat="server" type="submit"><i class="fa fa-lock"></i> SIGN IN</button>
Output: So far, the page i intend to redirect the user to is being loaded every time i click the submit button, irrespective of the userid/password.
Question: What I want to do is compare the values of the 2 inputs here with the values in my SQLServer db using c#.
Also, i know the c# code for setting up connection and comparing values with db for web forms. So, what specific changes to bring to that code for html form inputs?
Please help. Thanks.
EDIT: Sorry for not providing the back end code. Here(ignore any trivial syntax error):
public partial class StaffLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Login_Click(object sender, EventArgs e)
{
String getTextValuesUserID = Page.Request.Form["userid"].ToString();
String getTextValuesPassword = Page.Request.Form["password"].ToString();
//setting up connection with database
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\Pavel\\Documents\\Visual Studio 2013\\WebSites\\IMS\\App_Data\\DatabaseIMS.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Doctor where userid=#userid and password=#password", con);
cmd.Parameters.AddWithValue("#userid", getTextValuesUserID);
cmd.Parameters.AddWithValue("#password", getTextValuesPassword);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
// Response.Redirect("UserLoggedIn.aspx");
Response.Redirect("HomeDoc.aspx");
}
else
{
//javascript for invalid username and password Alert box
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and password')</script>");
}
}
}
You have multiple problems in your code, I'll point out just few of them. Before putting this site online, PLEASE, do some research on proper C# programming, because this is just plain wrong...
1.) if you use input fields with runat attribute, you can access their values in code-behind using their IDs! It's much better than to search for them in Request collection
so in your case, instead of
string getTextValuesPassword = Page.Request.Form["password"].ToString();
you can just say
string myPassword = password.Text;
2.) you should learn to close SqlConnection and dispose of external resources
3.) every time you store user's password, you SHOULD NEVER store it in plain text!!! Learn about proper hashing ASAP.
4.) you should never store connection string like this in .cs file. It can change or you may have to use it on multiple places. Store it at least in web.config
5.) .....
To address your specific problem, you are indeed comparing the values to the database values, BUT, you're not actually logging in the user. You need to do some research at least on basic Forms authentication, or if you need a more advanced scenario, you can use ASP.NET Identity.
I am creating a social network website as facebook, but that website has some errors with posing status , i used following code to post status. I called this method on page_Load event and post button
private DataSet GetData()
{
string CS=ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter da = new SqlDataAdapter("Select * from PhotoStatusProfile WHERE Email = '" + Session["Email"].ToString() +"'",con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
This is html code
<asp:Repeater runat="server" ID="Repeater1">
<ItemTemplate>
<div class="yourDivClass" style="border-top: thin none #BBCEB3; border-bottom: thin none #BBCEB3; padding: 10px; height: 121px; width: 548px; margin-top: 10px; right: 10px; left: 10px; border-left-width: thin; margin-left: 15px; background-color: #e9eaee; border-left-color: #BBCEB3; border-right-color: #BBCEB3;">
<br />
<div style="width: 58px; height: 62px">
<asp:Image ID="Image1" runat="server" Height="59px" ImageAlign="Top" ImageUrl="~/Profile/Image/supun_Profilemini.jpg" Width="55px" />
</div>
<div style="width: 307px; height: 21px; margin-left: 65px; margin-top: -60px">
<asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Names="Arial" ForeColor="#000066" ><%#Eval("name") %> </asp:Label>
</div>
<div style="height: 22px; width: 461px; margin-left: 78px; margin-top: 11px"> <asp:Label ID="Label8" runat="server"><%#Eval("Status") %></asp:Label>
<br><br>
</div>
</div>
</ItemTemplate>
post button cs code
protected void Post_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
try
{
string inserQuery = "insert into PhotoStatusProfile(Name,Status,Email) values (#Name,#Status,#e)";
SqlCommand commm = new SqlCommand(inserQuery, conn);
commm.Parameters.AddWithValue("#Name", ProfileName.Text);
commm.Parameters.AddWithValue("#Status",TextBox1.Text);
commm.Parameters.AddWithValue("#e", Label1.Text);
commm.ExecuteNonQuery();
Label1.Text = Session["Email"].ToString();
}
catch (Exception ex)
{
Response.Write("Error -->" + ex.ToString());
conn.Close();
}
// LoadData();
Repeater1.DataSource = GetData();
Repeater1.DataBind();
TextBox1.Text = "";
}
But After i'm posting some status I faced some errors.
1,On this website, my new post displayed on bottom and oldest one on top but i want new post to top and others Gradually top to bottom ,(descending order by considering time)
when i posted big status, it will display Like this.
I want to fix this also.
Thanks
You should think about storing some kind of date for each post. Then you can get a sorted list from the database. Something like this:
SqlDataAdapter da = new SqlDataAdapter("Select * from PhotoStatusProfile WHERE Email = '" + Session["Email"].ToString() +" order by CreatedAt desc'",con);
This would also allow you to show a "posted"-Date, show posts by day/week/month etc.
Reversing Repeater order
To make a long word wrap you can apply css:
word-wrap: break-word;
I am creating a social network website as facebook, but that website has an error with posing status , i used following code to post status.This code is on page load,
Label1.Text = Session["Email"].ToString();
if (!IsPostBack)
{
//load data
string db = "";
db = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(db);
con.Open();
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT Name,Status FROM [PhotoStatusProfile] WHERE Email = #Email";
cmd.Parameters.AddWithValue("#Email", Session["Email"].ToString());
cmd.Connection = con;
SqlDataReader dr;
dr = cmd.ExecuteReader();
string status = "";
string name = "";
while (dr.Read())
{
System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
Label nameLabel = new Label();
status += dr["Status"].ToString();
name += dr["name"].ToString();
nameLabel.Text = name;
Label statusLabel = new Label();
statusLabel.Text = status;
div.Controls.Add(nameLabel);
div.Controls.Add(statusLabel);
container.Controls.Add(div);
}
con.Close();
}
I am passing value to a div which name is container.
When i write a status saying hi,and click the post button but nothing happen, then i refresh the page, and it has posted like this
2nd time i do the same thing saying hello, this is the result of it.
This is container. it's a name of a div tag
<div id="container" runat="server"> </div>
This is post button event
string inserQuery = "insert into PhotoStatusProfile(Name,Status,Email) values (#Name,#Status,#e)";
SqlCommand commm = new SqlCommand(inserQuery, conn);
commm.Parameters.AddWithValue("#Name", ProfileName.Text);
commm.Parameters.AddWithValue("#Status",TextBox1.Text);
commm.Parameters.AddWithValue("#e", Label1.Text);
commm.ExecuteNonQuery();
I want to post the status for down to down,
Could anybody tell me , what should i do to prevent this errors. Thaks
I'd suggest you to do the following re-factoring to your code.
Extract the code between following if block in your Page_Load and create a method called LoadData().
if(!IsPostBack)
{
LoadData();
}
Then in your Post button's click event call this LoadData() method again just after saving your new post to the database.
Instead of Labels to display values use DIVs (I mean nameLabel and statusLabel)
Also add following style to these DIVs
style="float:left;"
This is how you'd add it in code behind
div.Style.Add("float", "left");
UPDATE 1
Here's how you'd add DIVs instead of Labels.
HtmlGenericControl divContainer = new HtmlGenericControl("div");
HtmlGenericControl nameDiv = new HtmlGenericControl("div");
// Not sure why you concatenate Name and Status here. I'll just use one value per each row
// status += dr["Status"].ToString();
// name += dr["name"].ToString();
nameDiv.InnerText = dr["name"].ToString();
nameDiv.Style.Add("float", "left");
divContainer.Controls.Add(nameDiv);
HtmlGenericControl statusDiv = new HtmlGenericControl("div");
statusDiv.InnerText = dr["Status"].ToString();
statusDiv.Style.Add("float", "left");
divContainer.Controls.Add(statusDiv);
container.Controls.Add(div);
UPDATE 2
Since you've adopted #mybirthname solution (using a Repeater) I'll just give you the design you want based on DIVs.
<asp:Repeater runat="server" ID="Repeater1">
<ItemTemplate>
<%--This is your template--%>
<div style="margin-top: 5px;">
<div style="padding: 2px; border: 1px solid black; background-color:Silver; display:table; width:600px;">
<div style="float:left;">
<div style="padding: 4px">
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/my-avatar.PNG" /> <%--Give the correct path to your image--%>
</div>
</div>
<div>
<div style="font-size: 16px; font-family: Arial, Helvetica, sans-serif; font-weight: bold; padding-top: 4px;">
<%#Eval("name") %>
<div style="float:right; font-size: 10px;">9:00 am</div> <%--If you need to have a time stamp for each entry make use of this div--%>
</div>
<div style="width:500px;"><%#Eval("Status") %></div>
</div>
</div>
</div>
<%--End template--%>
</ItemTemplate>
</asp:Repeater>
From what I see you are adding the div to container and nameLabel, StatusLabel to div on every iteration of the DataReader. Probably this is not your intention, You want to add them once, because you are storing in status all values of Status row.
while (dr.Read())
{
status += dr["Status"].ToString();
name += dr["name"].ToString();
}
System.Web.UI.HtmlControls.HtmlGenericControl div = new
System.Web.UI.HtmlControls.HtmlGenericControl("div");
container.Controls.Add(div);
Label nameLabel = new Label();
nameLabel.Text = name;
div.Controls.Add(nameLabel);
Label statusLabel = new Label();
statusLabel.Text = status;
div.Controls.Add(statusLabel);
Also it will be good idea to put some ID to the labels. I advice you to put labels and div always and just make them visible false if there are no values in them.
Also if you add dynamically controls do it always in CreateChildControls() method.
EDIT: For what you want(written in my comments) you need a repeater. Check this tutorial in MSDN
<div id="container">
<asp:Repeater runat="server" ID="Repeater1">
<ItemTemplate>
<div class="yourDivClass">
<asp:Label runat="server"> <%#Eval("Status") %> </asp:Label>
<asp:Label runat="server"> <%#Eval("name") %> </asp:Label>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
And in the code behind in Page_Load method:
if(!PostBack)
{
//in data set you will have dataTable with all rows and this rows should contain Name and Status columns
Repeater1.DataSource = dataSet;
Repeater1.DataBind();
}
Im trying to display name, description and a picture from my database with a repeater.
The Name and Description works as they should but the images won't show up. The images is located in a folder in my project and I'm trying to access them with a string that i have stored in the database "path" column.
oh, but if I look at the source code of the browser the src="" looks good, and i can even look at the pic in the browser if i paste the src to it..
Heres my code:
<head runat="server">
<title></title>
<style type="text/css">
.bilder {width:300;
height:200;
margin: 10px;
border: 1px solid black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater runat="server" ID="minRepeater">
<ItemTemplate>
<div class="wrapper">
<h1><%# DataBinder.Eval(Container.DataItem, "Name") %></h1>
<span id="desc"><%# DataBinder.Eval(Container.DataItem, "Description") %></span><br />
<img src="<%# DataBinder.Eval(Container.DataItem, "Path") %>" alt="test" class="bilder" />
<asp:Image ID="Image1" CssClass="bilder" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "Path")%>' runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
and codebehind:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = connectionstring;
SqlCommand com = new SqlCommand();
com.CommandText = "SELECT * FROM Pictures";
com.Connection = con;
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = com;
DataTable dt = new DataTable();
ad.Fill(dt);
Response.Write(dt.Rows.Count);
minRepeater.DataSource = dt;
minRepeater.DataBind();
}
(yes i know that my code isn't safe. at all.)
here's how it looks in a browser:
any ideas? :)
You may run it in Firebug or Chrome and see if the images are not found (404) and theirs path.
The error you're getting Not allowed to load local resource sounds like you are trying to load using a path on your local system. Trying using Server.MapPath with a relative path to the file, for example:
Server.MapPath("~/images/my-image.jpg");
Is your path like C:\\Images\etc...? If you are getting "Not allowed to load local resource", you should try your paths with relative paths.. if you dont have them in the WebSite you should make a copy of the image to the site and render that path. You are facing security problems.