I am new to asp.net, and what I want to know is how to bind data directly into a custom div
without using things such as data grid or any other thing, let's say I want to bind a description for something stored in my sql DB.
In PHP i used to do this:
<p>
<?php echo $row_RecordSetName['col']; ?>
</p>
But how to do in asp.net using C# in a webform?
I tried to do it in a dataset thing like so but it keeps giving errors:
<p>
<%= Dataset.DB[0].colNAME.ToString() %>
</p>
as well as i tried doing the following stupid way :
try
{
for (int i = 1; i < 7; i++)
{
SqlConnection cn = new SqlConnection("Data Source=server;Initial Catalog=db;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM mallsdb where mall_un='" + i + "'", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
MallsDS tds = new MallsDS();
da.Fill(tds, tds.Tables[0].TableName);
string MallPIC = Convert.ToString(tds.mallsdb[0].mall_pic);
string MallNAME = Convert.ToString(tds.mallsdb[0].mall_name);
string MallUn = Convert.ToString(tds.mallsdb[0].mall_un);
string MallDESP;
string check_desp = Convert.ToString(tds.mallsdb[0].mall_desp);
if (check_desp.Length < 50)
{
MallDESP = check_desp;
}
else
{
string under = check_desp.Substring(0, 30);
MallDESP = under + "....";
}
Result[i] = "<div class='malls'>" + "<img src='images/" + MallPIC + "' width='250' height='250' />" + "<a class='namer' href='malls_private.aspx?mall_un=" + MallUn + "'><h1>" + MallNAME + "</h1></a><p>" + MallDESP + "</p></div>";
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
Label1.Text = Result[1];
Label2.Text = Result[2];
Label3.Text = Result[3];
Label4.Text = Result[4];
Label5.Text = Result[5];
Label6.Text = Result[6];
In C#, you can do something like <div runat='server' id='divWhateverDiv'> in the aspx and then in the actual C# code (not in the aspx itself) you can reference the div element as a normal C# variable by its id, and do something like divWhateverDiv.innerHTML = "whatever"; Visual Studio's intellisense will help you with the actual capitialization of the members and such. What you're trying to do is more like old asp than asp.net
thanks friends and in the following is the answer to my question, as i read about it in microsoft MSDN.
<%# Page language="c#" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
SqlConnection cnn = new
SqlConnection("server=(local);database=pubs;Integrated Security=SSPI");
SqlDataAdapter da = new SqlDataAdapter("select * from authors", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "authors");
Repeater1.DataSource = ds.Tables["authors"];
Repeater1.DataBind();
}
</script>
<html>
<body>
<form id="WebForm2" method="post" runat="server">
<asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"au_id") %><br>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
Related
Hello I did build a autocomplete text field for my project:
HTML Coding:
<!-- Autocomplete Function -->
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender" runat="server" CompletionSetCount="10" TargetControlID="input_source"
ServiceMethod="GetCompletionList" CompletionInterval="100" EnableCaching="false" MinimumPrefixLength="1">
</ajaxToolkit:AutoCompleteExtender>
<!--Inputfield Autocomplete-->
<asp:TextBox autocomplete="on" id="input_source" OnTextChanged="input_source_TextChanged" runat ="server" class="form-control" placeholder="Please enter"></asp:TextBox>
Code behind C#:
//Autocomplete Field
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCompletionList(string prefixText, int count)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = lr_sqlserver;
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "SELECT TOP 5 Source FROM" + " " + selected_table + " " + "WHERE Source like '%' + #Search + '%'";
com.Parameters.AddWithValue("#Search", prefixText);
com.Connection = con;
con.Open();
List<string> suggestions = new List<string>();
using (SqlDataReader sdr = com.ExecuteReader())
{
while (sdr.Read())
{
suggestions.Add(sdr["Source"].ToString());
}
}
con.Close();
return suggestions;
}
}
}
Now I want to call the following function everytime I select a suggestion from the autocomplete function. Is something like this possible?
protected void input_source_TextChanged(object sender, EventArgs e)
{
string source = input_source.Text;
using (
SqlConnection com = new SqlConnection())
{
//SQL Server
com.ConnectionString = lr_sqlserver;
//Conncection establish
com.Open();
//Get SQL Information
SqlCommand select = new SqlCommand("select target from " + selected_table + " where source = #param", com);
select.Parameters.AddWithValue("#param", source);
string result;
result = (string)select.ExecuteScalar();
if (result != null)
{
input_target.Text = result;
}
}
}
You would need to put your TextBox inside an UpdatePanel and on the TextBox set AutoPostBack="True"
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox autocomplete="on" id="input_source" OnTextChanged="input_source_TextChanged" runat ="server" class="form-control" placeholder="Please enter" AutoPostBack="True"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
I'm doing a project in ASP.net and with SQL Server. I'm calling a stored procedure on user login screen to authenticate the user. But when I call the stored procedure, the entire page needs to be refreshed in order to get the data.
How can I achieve the same without refreshing the page?
This is my current code
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '"+Pwd+"'";
cmd = new SqlCommand(sql, cn.connect());
dr = cmd.ExecuteReader();
if(dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}
Use Ajax Extension, Here is the quick example:
.aspx File
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox runat="server" id="username" name="username" placeholder="Enter Username"></asp:TextBox>
<asp:TextBox name="passwd" ID="passwd" runat="server" placeholder="Enter Password"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Login" onclick="Button1_Click" />
<br />
<asp:Label ID="LblError" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
aspx.cs File - add this to Click event of Login Button
protected void Button1_Click(object sender, EventArgs e)
{
string sql = "";
SqlConnection cn = null;
SqlCommand cmd = null;
SqlDataReader dr = null;
string User = username.Text;
string Pwd = passwd.Text;
//cn = "<< your connection string>>";
try
{
cn.Open();
// Your code
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '" + Pwd + "'";
cmd = new SqlCommand(sql, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}
}
catch (Exception exce)
{
LblError.Text = exce.Message;
}
finally
{
cn.Close();
}
}
You can find UpdatePanel and ScriptManager under Toolbox -> Ajax Extension
Use try-catch block to handle runtime exceptions.
Based on the code you have, in Web Forms you can:
use an Update Panel;
or Page/Web Method
or a simple(r) Web handler (ashx)
If you want to load the data without refreshing the page. you can expose webservice method or create page method then you can call ASP.NET page method through ajax
[WebMethod]
public static string Insert_Data(string user, string pwd)
{
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '"+Pwd+"'";
cmd = new SqlCommand(sql, cn.connect());
dr = cmd.ExecuteReader();
if(dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}
}
Client Side
$(document).ready(function () {
$('#btnsubmit').click(function () {
var name = $('#user').val();
var sex = $('#pwd').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/Insert_Data',
data: "{'user':'" + user+ "','pwd':'" + pwd + "'}",
async: false,
success: function (response) {
alert("Record saved successfully..!!");
},
error: function () {
alert("Error");
}
});
});
});
There are 3 possible ways I know of:
1) using update panel:
see example: http://www.aspdotnet-pools.com/2014/07/ajax-login-form-in-aspnet-using-cnet.html
2) using webmethod:
see example: http://www.aspforums.net/Threads/133296/Develop-simple-AJAX-Login-form-using-jQuery-in-ASPNet/
3) using tiered coding:
see example: https://www.codeproject.com/Articles/170882/jQuery-AJAX-and-HttpHandlers-in-ASP-NET
I prefer method 3 coding as it is more flexible and the tiered coding concept is portable to other web programming platform.
I'm trying to insert content to my local database from a textbox inside a repeater element, in a post - comment way. So far I've tried looping on all the generated rows to find the specific textbox but I have had no luck, either the insert goes empty, or I get 1 insert per preexisting row, or I get the same value inserted over and over again through different posts.
I finally tried to pass the post id to the itemfinder and it's kind of working, but the "comm_contenido" inserts from the textbox are still going empty to the database.
My question is what it the correct and more direct way to handle these kind of inserts from within a Repeater?.
C#:
protected void Button1_Command(object sender, CommandEventArgs e)
{
string postid = e.CommandArgument.ToString();
string emailcc = Session["EMAIL"].ToString();
string user_id = Session["ID"].ToString();
string usrnom = Session["NOMBRE"].ToString();
string usrfoto = Session["FOTO_URL"].ToString();
//string COMM_CONTENIDO = lblcomm.Text.ToString();
var COMM_fecha = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
TextBox txt2;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBD"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
int m = Int32.Parse(postid);
txt2 = (TextBox)Repeater_UsrPosts.Items[m].FindControl("txtcomentar");
string txt1 = txt2.Text;
cmd.CommandType = CommandType.Text;
cmd.CommandText = (#"INSERT INTO MIEMBROS_Comments (COMM_USER_ID, COMM_CONTENIDO, COMM_FECHA, COMM_USER_NOMBRE, COMM_USER_FOTO, COMM_POST_ID) VALUES ('"
+ user_id + "','" + txt1 + "','" + COMM_fecha + "','" + usrnom + "','" + usrfoto + "','" + postid + "');");
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
}
}
//txtpublica.Text = "";
traerposts();
}
ASP:
<asp:Repeater ID="Repeater_UsrPosts" runat="server" >
<ItemTemplate>
<!-- Post -->
<div class="post clearfix">
<div class="user-block">
<img alt="" src="<%#Eval("post_user_foto")%>" class="img-circle img-bordered-sm" />
<span class="username">
<%#Eval("post_user_nombre") %>
<i class="fa fa-times"></i>
</span>
<span class="description"><%#Eval("post_fecha") %></span>
</div>
<!-- /.user-block -->
<p>
<%#Eval("post_contenido") %>
</p>
<ul class="list-inline">
<li><i class="fa fa-share margin-r-5"></i>Share</li>
<li><i class="fa fa-thumbs-o-up margin-r-5"></i>Like
</li>
<li class="pull-right">
<asp:LinkButton ID="bttnabrircomentarios" runat="server" class="link-black text-sm">
<i class="fa fa-comments-o margin-r-5"></i>Comments</asp:LinkButton>
</li>
</ul>
<asp:TextBox ID="txtcomentar" runat="server" class="form-control input-sm" placeholder="Escribe un comentario" EnableViewState="False"></asp:TextBox>
<%# Eval("post_id") %> -
<asp:Button ID="Button1" runat="server" Text="Button"
OnCommand="Button1_Command" CommandName="myCommand"
CommandArgument='<%# Eval("post_ID") %>' />
<br />
</div>
<!-- /.post -->
</ItemTemplate>
</asp:Repeater>
You can reach the TextBox Control by assigning OnTextChanged to it, and you can also assign its AutoPostBack to true if you wanted to reach the data immediately.
but you should use if(!IsPostBack) before you bind your data to your repeater, so it doesn't reset your Controls before you could reach the data.
OnTextChanged needs two parameter, one of them is the sender object which is calling it, That's your TextBox, something like..
ASP
<asp:Repeater ID="RepeaterExample" runat="server"><ItemTemplate>
<asp:TextBox runat="server" ID="TextBoxExample" AutoPostBack="True" OnTextChanged="TextBoxExample_OnTextChanged"/>
</ItemTemplate></asp:Repeater>
Behind Code
protected void TextBoxExample_OnTextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox) sender;
//Response.Write(txt.Text);
//or whatever you want to do with it.
}
and if you wanted to use it with Button_OnClick, you should use like a global string you can call later, you can do something like this..
ASP
<asp:Button runat="server" ID="ButtonExample" OnClick="ButtonExample_OnClick"/>
Behind Code
private string text = "";
protected void TextBoxTest_OnTextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
text = txt.Text;
}
protected void ButtonExample_OnClick(object sender, EventArgs e)
{
//Response.Write(text);
}
but the last method will take the value of the last TextBox whose text has changed, unless you add it together like..
text += txt.Text;
Hope, I could help..
This were the changes that worked for me to locate the specific textbox and prevent posting unwanted data.
C#:
protected void Button1_Command(object sender, CommandEventArgs e)
{
string postid = e.CommandArgument.ToString();
string emailcc = Session["EMAIL"].ToString();
string user_id = Session["ID"].ToString();
string usrnom = Session["NOMBRE"].ToString();
string usrfoto = Session["FOTO_URL"].ToString();
var COMM_fecha = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Control s = (Control)sender;
TextBox tb = (TextBox)s.NamingContainer.FindControl("txtcomentar");
tb.ReadOnly = true;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBD"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
string txt1 = tb.Text;
cmd.CommandType = CommandType.Text;
cmd.CommandText = (#"INSERT INTO MIEMBROS_Comments (COMM_USER_ID, COMM_CONTENIDO, COMM_FECHA, COMM_USER_NOMBRE, COMM_USER_FOTO, COMM_POST_ID) VALUES ('"
+ user_id + "','" + txt1 + "','" + COMM_fecha + "','" + usrnom + "','" + usrfoto + "','" + postid + "');");
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
}
}
traerposts();
}
And on the ASP I added the property EnableVIewState="true" to the textbox and also to the repeater.
At last, most important, I added if (!Page.IsPostBack) to the onload event.
And with all this together the comments on each post are being inserted correctly.
I'm writing the nodes of an XML to the database columns but I want to delete all (*) from the database before XML is written to the table again.
Right now if a user with userid '100' is inserted into the db, the code doesn't check for dupes and I'll have more than 1 userid '100's in the db. I need to check if the column id (for example) matches the id node of the xml. if there is a match, update the v and a nodes, if no match in the table then insert the id, v, and a nodes into the table
I created a function, private void deleteFromDb(string table) but I cant seem to call it (if I did it correctly in the first place) before the XML data is inserted into the table. But this wipes out all the data but the last person who accesses the page
<%# Page Language="C#"%>
<%# Import namespace="System.Net"%>
<%# Import namespace="System.Data"%>
<%# Import namespace="System.Data.SqlClient"%>
<%# Import namespace="System.IO"%>
<%# Import namespace="System.Xml"%>
<%# Import Namespace="System" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server" language="C#">
public class XML
{
internal string connString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString();
private void add2Db(string table, string sqlRows, string sqlValues)
{
string sql = String.Format("INSERT INTO {0} ({1}) VALUES ({2})", table, sqlRows, sqlValues);
using (SqlConnection dbConn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(sql, dbConn))
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
}
private void deleteFromDb(string table)
{
string sql = String.Format("DELETE *", table);
using (SqlConnection dbConn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(sql, dbConn))
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
}
public void parseXML(XmlDocument doc)
{
string tsLogpro = "";
string sqlRows = "";
string sqlValues = "";
//SELECT NODE: logPro
foreach (XmlNode logPro in doc.SelectNodes("broadcasting"))
{
tsLogpro = logPro.SelectSingleNode("#ts").InnerText;
//SELECT CHILD NODE: logPro
foreach (XmlNode child in logPro.ChildNodes)
{
//GET ROWS
foreach (XmlNode rows in child.Attributes)
{
sqlRows += rows.Name + ", ";
}
//GET VALUES
foreach (XmlNode values in child.Attributes)
{
sqlValues += "'" + values.InnerText + "', ";
}
sqlRows = sqlRows.Substring(0, sqlRows.Length - 2);
sqlValues = sqlValues.Substring(0, sqlValues.Length - 2);
//Response.Write("\n\n");
//Response.Write(sqlRows);
//Response.Write("\n" + sqlValues);
add2Db("flashcoms_chat7_broadcast", sqlRows, sqlValues);
sqlValues = "";
sqlRows = "";
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ExpiresAbsolute = DateTime.Now;
Response.AddHeader("Content-type", "text/plain");
HttpRequest request = HttpContext.Current.Request;
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
XmlDocument doc = new XmlDocument();
string s = reader.ReadToEnd();
if (Request.Params["action"] != string.Empty && Request.Params["action"] == "test")
{
doc.InnerXml = "" +
"<broadcasting ts=\"12345\">" +
"<u id=\"1\" v=\"true\" a=\"true\" />" +
"<u id=\"2\" v=\"true\" a=\"true\" />" +
"<u id=\"3\" v=\"true\" a=\"false\" />" +
"<u id=\"4\" v=\"true\" a=\"true\" />" +
"<u id=\"5\" v=\"true\" a=\"true\" />" +
"</broadcasting>";
}
else if (!string.IsNullOrEmpty(s))
{
doc.InnerXml = s;
}
// Starting at line 111 in your original post
XML oXML = new XML();
oXML.deleteFromDb("f_chat7_broadcast")
oXML.parseXML(doc);
Response.Write("Done");
Response.End();
}
/*
*
*
SET ANSI_NULLS ON
GO
USE [DB]
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[f_chat7_broadcast](
[id] [nchar](100) NULL,
[v] [nchar](10) NULL,
[a] [nchar](10) NULL
) ON [PRIMARY]
GO
*
*/
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>blah blah</title>
</head>
<body>
<form id="Form2" method="post" runat="server"><% Page_Load(null, null); %></form>
</body>
</html>
this
string sql = String.Format("DELETE *", table);
should be
string sql = String.Format("DELETE FROM {0}", table);
another point:
as far as I can see you don't have setup any exception handling (try / catch...) which is a bad practice...
Hi im wondering if its possible to add a asp button to the code below, the code below adds an image and text from my database to a dynamic div on my asp page:
using System.Data.Odbc;
using System.IO;
public partial class UserProfileWall : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString();
PopulateWallPosts(theUserId);
}
private void PopulateWallPosts(string userId)
{
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("SELECT wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN User u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE wp.UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
{
//("SELECT wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN [User] u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
using (OdbcDataReader reader = cmd.ExecuteReader())
{
test1.Controls.Clear();
while (reader.Read())
{
System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
div.Attributes["class"] = "test";
//div.Style["float"] = "left";
div.ID = "test";
Image img = new Image();
img.ImageUrl = String.Format("{0}", reader.GetString(1));
// this line needs to be represented in sql syntax
//img.ImageUrl = "~/userdata/2/uploadedimage/batman-for-facebook.jpg";
img.AlternateText = "Test image";
div.Controls.Add(img);
div.Controls.Add(ParseControl(String.Format("   "+"{0}", reader.GetString(0))));
div.Style["clear"] = "both";
test1.Controls.Add(div);
}
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString();
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings) VALUES (" + theUserId + ", '" + TextBox1.Text + "')", cn))
{
cmd.ExecuteNonQuery();
}
}
PopulateWallPosts(theUserId);
}
}
Here is the strange thing tho, if I do manage to add a button similar to the way I have added an image, how would I call that button, for example:
I want to call this button "delete" and add code to delete the text in my database related to that div, but if there is multiple divs(there all named the same div id=test) with text and they all have the same asp button how would I be able to tell the button to only delete the current text(in the db) for the current div??
My database stores the information like so:
Im thinking I would have to use idwallposting but not sure how?
Also to give a visual representation of how it looks it may help aid in the understanding:
My css and asp:
div#test1 {
}
div .test {
width:90%;
z-index:1;
padding:27.5px;
border-top: thin solid #736F6E;
border-bottom: thin solid #736F6E;
color:#ffffff;
margin:0 auto;
white-space: pre;
white-space: pre-wrap;
white-space: pre-line;
word-wrap: break-word;
}
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js" type="text/javascript"></script>
<p>
<asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3"
Height="47px" Width="638px"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Post Message" Width="98px"
onclick="Button1_Click" />
</p>
<p>
</p>
<style type="text/css">
img {border-width:0px; width:100px; height:100px;}
</style>
<div id="test1" runat="server" />
</div>
</asp:Content>
Why not give each div a unique ID like div.ID = "test" + idWallPostings; ?
It is not a good idea to have non-unique IDs for any element.
Regarding your main problem, why not use one of the templated data controls like Repeater or ListView and add a Command handler. Then in the template add the button with a command argument for the current data item's data key.
see: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemcommand.aspx
You can see how the the button is used to carry additional information in its click event:
<asp:LinkButton runat="server"
ID="SelectEmployeeButton"
Text="Add To List"
CommandName="AddToList"
CommandArgument='<%#Eval("LastName") + ", " + Eval("FirstName") %>' />
and how it is retrieved and used (it is accessed using e.CommandArgument):
protected void EmployeesListView_OnItemCommand(object sender, ListViewCommandEventArgs e)
{
if (String.Equals(e.CommandName, "AddToList"))
{
// Verify that the employee ID is not already in the list. If not, add the
// employee to the list.
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
string employeeID =
EmployeesListView.DataKeys[dataItem.DisplayIndex].Value.ToString();
if (SelectedEmployeesListBox.Items.FindByValue(employeeID) == null)
{
ListItem item = new ListItem(e.CommandArgument.ToString(), employeeID);
SelectedEmployeesListBox.Items.Add(item);
}
}
}
For deletion from database with C# in Visual Studio 2008 ASP.net write the following code by double-clicking on button:
protected void btndel_Click(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand cmd;
conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\THEGIRL\\Documents\\Visual Studio 2008\\WebSites\\WebSite72\\App_Data\\Database.mdf';Integrated Security=True;User Instance=True");
conn.Open();
cmd = new SqlCommand("Delete from logintable where username='"+txtdeluname.Text+"'",conn);
lbldel.Text = "Record is deleted";
cmd.ExecuteNonQuery();
conn.Close();
}