I am trying to insert a comment using repeater Control
my code in html
<asp:Repeater ID="repConcerns" runat="server" OnItemCommand="post" >
<ItemTemplate >
<div class="row col-md-12">
<div class="col-sm-2" style="background-color:#808080">
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("Pathh") %>' width="90px" Height="90px" CssClass="img-circle" title='<%#Eval("Name") %>'/> <br/><asp:LinkButton ID="LinkButton1" runat="server" Text='<%#Eval("Name") %>' CssClass="btn btn-info btn-sm" CommandName="btnMessage" CommandArgument='<%#Eval("Username") %>'></asp:LinkButton><br/>
</div>
<div class="col-sm-10" style="background-color:#808080" >
<asp:Label ID="Label1" width="100%" style="padding:7px;" runat="server" Enabled="false" Text='<%#Eval("Title") %>'> </asp:Label>
<asp:TextBox ID="txtMessage" placeholder="Empty Post" width="100%" style="padding:7px;" runat="server" Text='<%#Eval("Detail") %>' TextMode="MultiLine" Enabled="false" Height="100px"> </asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Eval("Sno") %>' />
<div class="bar"></div>
<asp:TextBox ID="txtcomment" runat="server" CssClass="form-control form-control-sm" placeholder="Comment / Write Openion Suggestion" TextMode="MultiLine" Height="40px"></asp:TextBox>
<asp:LinkButton ID="btn" runat="server" CssClass="btn btn-primary" CommandName="comment" CommandArgument='<%#Eval("Sno") %>' >Post</asp:LinkButton>
</div>
</div>
<div style="padding-bottom:10px;"></div>
<%--<br /> --%>
</ItemTemplate>
</asp:Repeater>
and C# code
protected void post(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName== "comment")
{
a = e.CommandArgument.ToString();
SqlConnection con = new SqlConnection(strconn);
SqlCommand com = new SqlCommand();
com.CommandText = "insert into Comments(Sno,Comment,Username)values('" +a+ "','" + txtcomment.Text + "','" + username + "')";
con.Open();
}
}
I do not know how to insert into table "Comment".
I have made a "Page" in which their are wall posts. I have included an option for Comment. The comment button appears as it should with every post. But i do not know how to insert comment in table "Comment". i am trying to insert comment with corresponding "Sno" of Posts saved in HiddenField. But when i try to write Text Box id there "txtcomment.text" it gives me error. How do i insert.
I've made some amendments to you original code - note the comments:
protected void post(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName== "comment")
{
//Find TextBox Control
TextBox txt = (TextBox)e.Item.FindControl("txtcomment");
var sno = e.CommandArgument.ToString();
SqlConnection con = new SqlConnection(strconn);
SqlCommand com = new SqlCommand();
com.CommandText = "INSERT INTO Comments(Sno,Comment,Username) VALUES (#SNO, #COMMENT, #USERNAME)";
com.Connection = con;
//Add Command Parameters
com.Parameters.AddWithValue("#SNO", sno);
com.Parameters.AddWithValue("#COMMENT", txt.Text);
com.Parameters.AddWithValue("#USERNAME", username);
con.Open();
//Execute Command
com.ExecuteNonQuery();
}
}
Related
I'm working in a Quiz Page where users can access and answers some questions. The problem I'm facing is when I want to display the possible answers of the questions. I want to display the options in a dropdownlist. I already have the questions in a datalist. Are there any ideas of how can I do it?
This is how it looks:
(In the arrows that I placed is where I want to display the options)
This is what users see
Here is what I have:
A FormQuiz.aspx:
<body style="background-color: #0f5298">
<form id="form1" runat="server">
<nav class="auto-style2" style="background-color: #d5f3fe">
<div class="auto-style3">
<a class="navbar-brand" href="#">
<img src="logo.png" alt="" class="auto-style1" />
Quiz
</a>
</div>
</nav>
<div class="card">
<asp:Label ID="LabelName" runat="server" Text="Seleccione un Quiz:" CssClass="lbl"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="ddl" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem Text="--- Seleccione ----" Value=" " />
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text="Instrucciones" CssClass="lbl"></asp:Label>
<asp:Label ID="LabelInstrucciones" runat="server" CssClass="I"></asp:Label>
<asp:Panel ID="Panel1" runat="server" CssClass="panelQ">
<asp:Label ID="Label2" runat="server" CssClass="section"></asp:Label>
<asp:DataList ID="DataList1" runat="server" CssClass="datalist">
<ItemTemplate>
<div style="margin-top: 2%">
<asp:Label ID="Label2" runat="server" Text='<%#Eval("Description") %>'></asp:Label>
</div>
<asp:DropDownList ID="DropDownOptions" runat="server" Width="200px" AppendDataBoundItems="true" AutoPostBack="true" DataSourceID="dsOptions" DataTextField="Options" DataValueField="Id">
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:DataList>
</asp:Panel>
</div>
</form>
</body>
This is how I get the questions in FormQuiz.aspx.cs:
public void SelectedSectionsTitlesQuestions(int id)
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
con.Open();
string querySection = #"SELECT Mant.Sections.Name
FROM Mant.Quizzes
INNER JOIN Mant.Questions ON Mant.Quizzes.Id = Mant.Questions.Quiz_Id
INNER JOIN Mant.Sections ON Mant.Questions.Section_Id = Mant.Sections.Id
WHERE Mant.Quizzes.Id =" + id;
string queryQuestion = #"SELECT Mant.Questions.Description
FROM Mant.Quizzes
INNER JOIN Mant.Questions ON Mant.Quizzes.Id = Mant.Questions.Quiz_Id
WHERE Mant.Quizzes.Id =" + id;
SqlDataAdapter ad2 = new SqlDataAdapter(querySection, con);
DataSet ds2 = new DataSet();
ad2.Fill(ds2);
Label lblsection = (Label)FindControl("Label2");
lblsection.Text = ds2.Tables[0].Rows[0]["Name"].ToString(); ;
DataList datalistQuestions = (DataList)FindControl("DataList1");
SqlDataAdapter ad = new SqlDataAdapter(queryQuestion, con);
DataSet ds = new DataSet();
ad.Fill(ds);
datalistQuestions.DataSource = ds;
datalistQuestions.DataBind();
FillDropdown();
con.Close();
}
}
This is how I populate the dropdown with a SqlDataSource:
public void FillDropdown()
{
using (SqlConnection con = new SqlConnection(#"Server =hncrsap-sql01; Database=HEDS;User Id = sa; Password=Lear2005; MultipleActiveResultSets=true;"))
{
con.Open();
List<int> Types = new List<int>(TypeQuestionsId());
for(int x=0; x < Types.Count(); x++)
{
int TQuestions_Id = Types[x];
string queryTypeQuestion = #"SELECT TypeQuestions_Id
FROM Mant.Questions
WHERE Quiz_Id=" + id_Quiz +
"AND TypeQuestions_Id=" + TQuestions_Id;
SqlCommand SelectCommand = new SqlCommand(queryTypeQuestion, con);
SqlDataReader myreader;
myreader = SelectCommand.ExecuteReader();
while (myreader.Read())
{
string querySelectOptions = #"SELECT Options, Id
FROM Mant.AnswerOptions
WHERE TypeQuestions_Id=" + TQuestions_Id;
SqlDataSource dsOptions = new SqlDataSource();
dsOptions.ID = "dsOptions";
this.Page.Controls.Add(dsOptions);
dsOptions.ConnectionString = "Server =hncrsap-sql01; Database=HEDS;User Id = sa; Password=Lear2005; MultipleActiveResultSets=true;";
dsOptions.SelectCommand = querySelectOptions;
}
}
con.Close();
}
// return values;
}
But I got this error in the SelectedSectionsTitlesQuestions method
You can configure another SqlDataSource and bind it to your drop-down list.
<asp:DropDownList ID="ddlEmployees" runat="server" DataSourceID="SqlDataSource1"
DataTextField="EmployeeName" DataValueField="EmployeeID" AppendDataBoundItems="true">
<asp:ListItem Text="Please select" Value="" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DB_9EF896_weddingConnectionString %%>"
SelectCommand="SELECT (FirstName + ' ' + LastName) AS EmployeeName, EmployeeID FROM Employees">
</asp:SqlDataSource>
Result
I am facing a problem with below code. When I click on Repsendbtn it stores the same session value of UsrNme into both columns Receiver and Sender, where it is supposed to save session value into Receiver and into Sender the value of tolbl
<asp:FormView ID="repmsgform" runat="server" DataKeyNames="mailno" Width="100%" >
<ItemTemplate>
<div class="col-lg-12">
<form class="well span8">
<div class="row">
<div class="span3">
<label>From</label>
<asp:Label ID="tolbl" runat="server" CssClass="form-control" Text='<%# Bind("Receiver") %>'></asp:Label>
<label>To</label>
<asp:Label ID="frmlbl" runat="server" CssClass="form-control" Text='<%# Bind("sender") %>'></asp:Label>
<label>Ads Title</label>
<asp:Label ID="MsgTitLbl" runat="server" CssClass="form-control" Text='<%# Bind("Mestitle") %>'></asp:Label>
<asp:Label ID="adsnummsglbl" runat="server" Text='<%# Bind("AdsID") %>' Visible="false" ></asp:Label>
<asp:Label ID="mailnolbl" runat="server" Text='<%# Bind("mailno") %>' Visible="false" ></asp:Label>
</div>
<div class="span5">
<label>Message</label>
<asp:TextBox ID="TextBox15" runat="server" TextMode="MultiLine" Height="150px" CssClass="form-control"></asp:TextBox>
</textarea>
</div>
<asp:Label ID="msgsentlbl" runat="server" Font-Size="Medium" ForeColor="#669900"></asp:Label>
<asp:Button runat="server" ID="Repsendbtn" Text="Send" CssClass="btn btn-primary pull-right" OnCommand=" Repsendbtn_Command" CommandArgument='<%# Bind ("mailno") %>'/>
<asp:Button ID="Closebtn" runat="server" Text="Close" CssClass="btn btn-default pull-right" OnCommand=" Closebtn_Command" />
</div>
</form>
</div>
</ItemTemplate>
</asp:FormView>
Code:
protected void Repsendbtn_Command(object sender, CommandEventArgs e)
{
if (Session["UsrNme"] != null)
{
using (SqlConnection cn = new SqlConnection(sc))
{
string SendMsgSQL = #"INSERT INTO mails (AdsID, Mestitle, Message, Receiver, sender, Date) VALUES (#AdsID, #Mestitle, #Message, #Receiver, #sender, #Date)";
using (SqlCommand SendMsgcmd = new SqlCommand(SendMsgSQL, cn))
{
cn.Open();
var user = Session["UsrNme"];
SendMsgcmd.Parameters.AddWithValue("#Receiver", user);
SendMsgcmd.Parameters.AddWithValue("#Message", ((TextBox)repmsgform.FindControl("TextBox15")).Text);
SendMsgcmd.Parameters.AddWithValue("#Mestitle", ((Label)repmsgform.FindControl("MsgTitLbl")).Text);
SendMsgcmd.Parameters.AddWithValue("#AdsID", ((Label)repmsgform.FindControl("adsnummsglbl")).Text);
SendMsgcmd.Parameters.AddWithValue("#Date", DateTime.Now);
SendMsgcmd.Parameters.AddWithValue("#sender", ((Label)repmsgform.FindControl("tolbl")).Text);
SendMsgcmd.ExecuteNonQuery();
viewmsgView.Visible = true;
}
}
}
else
{
// Consider throwing an error (if these fields are required)
}
}
If Click button in repeater control, delete data in database but not working. I use Visiual Studio 2013. My project ASP.Net Website and I am useing MasterPage and My Database connectionstring command in web.config.
This is default.aspx.cs file
static string yol = ConfigurationManager.ConnectionStrings["cs"].ConnectionString;
SqlConnection baglanti = new SqlConnection();
SqlCommand sorgu = new SqlCommand();
SqlDataReader oku;
protected void Page_Load(object sender, EventArgs e)
{
baglanti = new SqlConnection(yol);
sorgu.Connection = baglanti;
baglanti.Open();
if (!Page.IsPostBack)
{
sorgu.CommandText = "select * from blog";
oku = sorgu.ExecuteReader();
haber.DataSource = oku;
haber.DataBind();
oku.Close();
}
baglanti.Close();
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
baglanti.Open();
if (e.CommandName == "sil")
{
int id = Convert.ToInt32(e.CommandArgument);
sorgu.CommandText = "delete from blog where id=" + id;
sorgu.ExecuteNonQuery();
haber.DataBind();
}
baglanti.Close();
}
Default.aspx file
<form runat="server">
<asp:Repeater ID="haber" runat="server" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>
<li class="mix nature" data-name="Woodstump">
<img src="../img/work1.jpg" alt="" width="150px" height="150px">
<h4> <%# Eval("baslik") %> <br />
<asp:Button ID="Button1" Text="Button" runat="server" CommandName="sil" CommandArgument="<%# Eval("Id") %>" />
</h4>
</li>
</ItemTemplate>
</asp:Repeater>
</form>
Edit: If i use this command CommandArgument="<%# Eval("Id") %>", Exeption is "The server tag is not well formed"
if i use this command CommandArgument='<%# Eval("Id") %>', Not take exeption but not work(not delete data in database).
I think that you are sending the parameters revers.
Change this:
CommandArgument="sil" CommandName='<%# Eval("Id") %>'
To this:
CommandArgument='<%# Eval("Id") %>' CommandName="sil"
Here is the code that works:
protected void submitForMail(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\TravelJoansDB.mdb;";
string cmdstr = "INSERT INTO EmailList(FirstName,LastName,EmailAddress) VALUES (#FirstName, #LastName, #EmailAddress)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
TextBox tFirstName = (TextBox)FormView1.FindControl("FirstName");
TextBox tLastName = (TextBox)FormView1.FindControl("LastName");
TextBox tEmail = (TextBox)FormView1.FindControl("EmailAddress");
con.Open();
com.Parameters.AddWithValue("#FirstName", tFirstName.Text);
com.Parameters.AddWithValue("#LastName", tLastName.Text);
com.Parameters.AddWithValue("#EmailAddress", tEmail.Text);
com.ExecuteNonQuery();
con.Close();
}
Here is the code that doesn't:
protected void UpdatePic(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\TravelJoansDB.mdb;";
string cmdstr = "INSERT INTO BlogEntryItems(Picture) VALUES (#UpdatedPic)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
TextBox uPic = (TextBox)DataList1.FindControl("BEIPictureField");
con.Open();
com.Parameters.AddWithValue("#UpdatedPic", uPic.Text);
com.ExecuteNonQuery();
con.Close();
}
Here is the code containing the Datalist1 control:
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/TravelJoansDB.mdb"
SelectCommand="SELECT * FROM Table2 INNER JOIN [BlogEntryItems] ON Table2.ID=BlogEntryItems.BlogID WHERE ID=#ID" >
<SelectParameters>
<asp:QueryStringParameter Name="ID" QueryStringField="ID" />
</SelectParameters>
</asp:AccessDataSource>
<asp:DataList ID="DataList1" runat="server" DataSourceID="AccessDataSource1">
<ItemStyle />
<ItemTemplate>
<table>
<tr>
<td>
<br />
<asp:Image ID="Image1" CssClass="placePicCenter" runat="server"
BorderWidth="1px"
BorderColor="#EEEEEE"
ImageUrl='<%# "PlaceImages/" + Eval("Picture") %>' /><br />
<asp:TextBox ID="BEIPictureField" runat="server" Text='<%# Bind("Picture") %>' /><br />
<asp:Button ID="UpdatePicButton" runat="server" Text="Update" OnClick="UpdatePic" />
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label4" CssClass="placeBodyStyle" runat="server" Text='<%# Eval("PicText1") %>' />
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
These blocks of code are for two different buttons on two different pages. The error I get when I run the second block of code is "Object reference not set to an instance of an object." Any help would be appreciated.
This line is the probable cause, it is failing to find the control BEIPictureField thus the "Object reference not set to an instance of an object." error
TextBox uPic = (TextBox)DataList1.FindControl("BEIPictureField");
EDIT 1
Try this:
TextBox uPic = (TextBox)DataList1.Items[1].FindControl("BEIPictureField");
you will have to rewrite your logic to find the control in each item not the DataList since it is the parent you will not find it there.
I have Image in ItemTemplate that will be changing according to Username (ie lblPostedBy.Text). I have written code in onItemCommand of repeater control in C# Asp.net 4.0. But not working. Will you please help me.
protected void myrepeater_ItemCommand1(object source, RepeaterCommandEventArgs e)
{
// Actually lblPostedBy is a linkbutton and lblPostedBy.Text is 'username of the commenter'.
LinkButton lblPostedBy = (LinkButton)e.Item.FindControl("lblPostedBy");
con.Open();
cmd.CommandText = "select image from " + lblPostedBy.Text + " where id=1";
// 'image' column in table stores path of image like '~/image/image1.jpg'
cmd.Connection = con;
string imageurl = (string)cmd.ExecuteScalar();
con.Close();
Image Image1 = (Image)e.Item.FindControl("Image1");
Image1.ImageUrl = imageurl;
}
and
<asp:Repeater ID="myrepeater" runat="server"
onitemcommand="myrepeater_ItemCommand1">
<HeaderTemplate>
<table width="100%" style="font: 8pt verdana">
<tr style="background-color:#3C78C3">
<th>NEWS FEED</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td valign="top">
<asp:Image ID="Image1" runat="server" Height="50px" Width="50px" />
<asp:LinkButton ID="lblPostedBy" runat="server" onclick="lblPostedBy_Click" Text='<%#DataBinder.Eval(Container,"DataItem.postedby") %>' />   says : <br />
<asp:TextBox id="txtPost" runat="server" Width="100%" textmode="multiline" text='<%#DataBinder.Eval(Container,"DataItem.scraps")%>' ReadOnly="True" BackColor="#EFF3FB" BorderStyle="None"></asp:TextBox>
<%#DataBinder.Eval(Container,"DataItem.scraptime") %>
<br />
<asp:TextBox ID="TextBox2" runat="server" Visible="False" Width="80%"></asp:TextBox>
<asp:Button ID="btnDoneComment" runat="server" Text="Done" Visible="False" onclick="btnDoneComment_Click"/>
<br />
<hr style="border:dashed 1px blue" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Thanks in Advance,
Regards,
Nikhil
Instead of "cmd.CommandText = "select image from " + lblPostedBy.Text;"
Shouldn't it be
cmd.CommandText = "select image from TableName where pby = '" + lblPostedBy.Text + "'";
Better yet, add a parameter
cmd.CommandText = "select image from tablename where pby = #pby"
cmd.Parameters.Add(new SalParameter("#pby", lblPostedBy.Text);