Repeater - textbox content to database C# - c#

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.

Related

Call a function when autocomplete text is selected

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>

how to do Log IN with current User in the masterpage

how can i do a login with current user? the current user will be displayed in the masterpage of the default homepage and the label from the masterpage will inherit to the content pages of the master page.
here is my login page asp code:
<div class="container-fluid">
<form class="form-signin" runat="server">
<h1 class="form-signin-heading text-muted">Sign In</h1>
<asp:TextBox ID ="email" runat="server" CssClass="form-control" placeholder="Email Address"></asp:TextBox>
<asp:TextBox ID ="password" runat="server" CssClass="form-control" placeholder="Password" TextMode="Password"></asp:TextBox>
<br />
<asp:Button ID="btnLogIN" runat="server" CssClass="btn btn-primary btn-block" Text="Log In" OnClick="btnLogIN_Click" />
</form>
and my aspx.cs code is here and i dont know if this is correct.
protected void btnLogIN_Click(object sender, EventArgs e)
{
Utility u = new Utility();
string conn = u.connect();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand read = connUser.CreateCommand();
SqlDataReader reader = null;
int empid = 0;
string dbuser = "";
string dbpword = "";
string username = email.Text;
string passwords = password.Text;
string login = "Select * from MOSEFAccount where UserName = '" + username + "' AND Password = '" + passwords + "'";
try
{
connUser.Open();
read.CommandText = login;
reader = read.ExecuteReader();
}
catch
{
Console.WriteLine("Error");
}
while (reader.Read())
{
empid = reader.GetInt32(0);
dbuser = reader.GetString(1);
dbpword = reader.GetString(2);
}
if (username == dbuser && passwords == dbpword)
{
Response.Redirect("~/Default.aspx?ID=" + empid);
}
else
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type ='text/javascript'>");
sb.Append("alert('Invalid Account');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditHideModalScript", sb.ToString(), false);
}
connUser.Close();
}
Can you elaborate on the meaning of current user? Unless you login you are not logged in user but anonymous user.
Update:
Store the pulled data in Session object and access it anytime whenever and wherever you like. For example:
For storing details use:-
if (username == dbuser && passwords == dbpword)
{
Session["UserName"] = username;
Session["EmpId"] = empid;
Response.Redirect("~/Default.aspx?ID=" + empid);
}
For displaying use (in the master page):
<%=Session["UserName"]%>
<%=Session["EmpId"]%>
You can build upon this like creating a User class and then creating an instance of this class and storing the instance itself in Session.

dropdownlist not fetching values from table on OnSelectedIndexChanged

am trying to fetch values from database table on dropdownlist value change and display them in textbox. While selecting any value from the dropdownlist the page is refreshing but no values are displaying in the textbox and following are the codes:
Default.aspx
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>
Default.aspx.cs
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string ddl2value = DropDownList1.SelectedValue.ToString();
// fillDropdown3(ddl3, ddl2value);
SqlConnection objConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand objCmd2;
SqlDataReader objRdr2;
// String strCmd2;
objConn2.Open();
objCmd2 = new SqlCommand("SELECT code, rank, address FROM agen_mast WHERE name = " +
"'" + ddl2value.ToString() + "'", objConn2);
objRdr2 = objCmd2.ExecuteReader();
while (objRdr2.Read())
{
TextBox9.Text = (string)objRdr2["code"].ToString();
TextBox8.Text = (string)objRdr2["address"].ToString().ToUpper();
TextBox10.Text = (string)objRdr2["rank"].ToString().ToUpper();
}
objRdr2.Close();
objConn2.Close();
// Response.Write(ddl2value.ToString());
}
You could try something like this:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if(DropDownList1.SelectedValue !="-1"){
string ddl2value = DropDownList1.SelectedValue.ToString();
SqlConnection objConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand objCmd2;
SqlDataReader objRdr2;
objConn2.Open();
objCmd2 = new SqlCommand("SELECT code, rank, address FROM agen_mast WHERE name = " +
"'" + ddl2value + "'", objConn2);
objRdr2 = objCmd2.ExecuteReader();
while (objRdr2.Read())
{
TextBox9.Text = (string)objRdr2["code"].ToString();
TextBox8.Text = (string)objRdr2["address"].ToString().ToUpper();
TextBox10.Text = (string)objRdr2["rank"].ToString().ToUpper();
}
objRdr2.Close();
objConn2.Close();
}
}
And add a dummy ListItem with Value -1 as the first item in the DropDownList1 in the .aspx side. By the way, make sure you are sending the correct parameter to SqlCommand. Right now you are looking for a record with Name = 0. Also, ddl2Value is already of type string so you don't need to call ToString() inside SqlCommand

Itemcommand not firing on button click event in a datalist using c#

this is my offer.aspx inherits from masterpage
' />
my .cs file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
offerlistbind();
}
}
public void offerlistbind()
{
db1.strCommand = " select Offer.OfferID, Offer.OfferName,Offer.Amount,Offer.FromDate,Offer.ToDate,Offer.Description,bm_package.PackageName,bm_country.Country from Offer inner join bm_package on Offer.PackageID=bm_package.PackageID inner join bm_country on Offer.CountryID=bm_country.CountryID";
offerlistnew.DataSource = db1.DataSet();
offerlistnew.DataBind();
}
if i click the button instead of firing item command event item dataBound event is working
protected void offerlistnew_ItemCommand1(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "subscribe")
{
int ofid = Convert.ToInt32(e.CommandArgument);
Response.Redirect("http://ecom.bom.tv/default.aspx?Offer=" + ofid + "");
}
}
Please use Hyperlink in place of button. If you use asp button then first it will do post back then it will redirect to another page. But using hyperlink you can directly redirect to another page. You can also increase the performance using this.
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='http://ecom.bom.tv/default.aspx?Offer=<%# Eval("OfferID") %>'
Text="Subscribe"></asp:HyperLink>
OR
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "http://ecom.bom.tv/default.aspx?Offer=" + Eval("OfferID") %>'
Text="Subscribe"></asp:HyperLink>
Let me know if any concern.
use e.commandname in link button
if (e.CommandName == "sel")
{
//Code conn.Open();
int lblintid = Convert.ToInt32(e.CommandArgument.ToString());
string cmd2 = "UPDATE productsTs set recurrent=recurrent+30,biduser='" + HiddenField2.Value + "' where ID = " + e.CommandArgument + "";
SqlCommand x2 = new SqlCommand(cmd2, conn);
x2.ExecuteNonQuery();
conn.Close();
}else if(e.CommandName == "min")
{
//Code conn.Open();
int lblintid = Convert.ToInt32(e.CommandArgument.ToString());
string cmd2 = "UPDATE productsTs set recurrent=recurrent-30,biduser='" + HiddenField2.Value + "' where ID = " + e.CommandArgument + "";
SqlCommand x2 = new SqlCommand(cmd2, conn);
x2.ExecuteNonQuery();
conn.Close();
}

Add button to webpage via code behind in asp.net and delete dynamic db entrys

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("&nbsp&nbsp "+"{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();
}

Categories

Resources