ASP: Send a Request String from a Button onclick - c#

I'm using aspx and aspx.cs file.
I need to have buttons onclick event which send data to the cs file to do something with the database.
So far my only problem is how to send the data which is selected.
My aspx page is
<form id="form1" runat="server">
<asp:Button ID="city" runat="server" Text="London" value="London" onclick="Page_Load" />
<asp:Button ID="city" runat="server" Text="Paris" value="Paris" onclick="Page_Load" />
<asp:Button ID="city" runat="server" Text="Madrid" value="Madrid" onclick="Page_Load" />
</form>
and the aspx.cs page is
protected void Page_Load(object sender, EventArgs e)
{
String city= Request.QueryString["city"];
SqlConnection sqlCon = new SqlConnection("xx");
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("Select * from Table where City = city", sqlCon);
....
}
so the problem is that i don't know how to send the chosen value. How can i do it? Thanks

You are confusing Click event and Page Load event, here u go :
<form id="form1" runat="server">
<asp:Button ID="city" runat="server" Text="London" value="London" OnClick="Button_Click" />
<asp:Button ID="city" runat="server" Text="Paris" value="Paris" OnClick="Button_Click" />
<asp:Button ID="city" runat="server" Text="Madrid" value="Madrid" OnClick="Button_Click" />
</form>
protected void Button_Click(object sender, EventArgs e)
{
String city= Request.QueryString["city"];
SqlConnection sqlCon = new SqlConnection("xx");
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("Select * from Table where City = city", sqlCon)
}

Related

Cannot search on gridview C# aspnet

I'm implementing a search bar to filter GridView1. I followed this tutorial but when it doesnt work. I want to filter the UserID and show only the specific output match the user input. I clicked on search but nothing work, it just refreshed the page and nothing else.
aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Manager.Master" AutoEventWireup="true" CodeBehind="ExceptionReport.aspx.cs" Inherits="Bracelet.ExceptionReport" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="col-md-10">
<div class="content-box-large">
<div class="panel-heading">
<div class="panel-title">Admin Log Report</div>
</div>
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button Text="Search" runat="server"/>
<div class="panel-body">
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="UserID">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" />
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="UserEmail" HeaderText="UserEmail" SortExpression="UserEmail" />
<asp:BoundField DataField="logtime" HeaderText="logtime" SortExpression="logtime" />
</Columns>
</asp:GridView>
</div>
</div>
<asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="Bracelet.BraceletDataContext" EntityTypeName="" TableName="Users">
</asp:LinqDataSource>
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="Bracelet.BraceletDataContext" EntityTypeName="" TableName="Users" Where="UserRole == #UserRole">
<WhereParameters>
<asp:Parameter DefaultValue="Admin" Name="UserRole" Type="String" />
</WhereParameters>
</asp:LinqDataSource>
</div>
</asp:Content>
Full code .cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace Bracelet
{
public partial class ExceptionReport : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
protected void Search(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["BraceletConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT UserID, UserName, UserEmail, logtime FROM [User] WHERE UserID LIKE '%' + #UserID + '%'";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UserID ", txtSearch.Text.Trim());
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}
}
}
Not too bad.
but, there are few errors and issues.
first up, you have search button - but it has no "id" assigned.
You probably should get in the habit of simple drag + drop the button in from the tool box.
So, we now have this for the button and the grid:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button ID="cmdSearch" runat="server" Text="Search" />
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="UserID">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" />
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="UserEmail" HeaderText="UserEmail" SortExpression="UserEmail" />
<asp:BoundField DataField="logtime" HeaderText="logtime" SortExpression="logtime" />
</Columns>
</asp:GridView>
NOTE carefull in above, how we gave the button a "ID"
So, our basic code to load up the grid?
FYI: huge love, hugs, high-5's for checking is-post back!!!
(always, always do that!!!).
So, our code to load things up can thus look like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
this.BindGrid();
}
void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["BraceletConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT UserID, UserName, UserEmail, logtime FROM [User]", con))
{
// optional text box filter (blank = all)
if (txtSearch.Text != "")
{
cmd.CommandText += " WHERE UserID LIKE '%' + #UserID + '%'";
cmd.Parameters.Add("#UserID", SqlDbType.Text).Value = txtSearch.Text;
}
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
Note how we did not need that data adaptor - not needed.
However, we still not created the code stub for the button click (that's why your code is not working - you did not give your button a "id"
So, in the designer - double click on the button. That will create the "event" for you, and jump to the code editor, and we have this:
protected void cmdSearch_Click(object sender, EventArgs e)
{
this.BindGrid();
}
so, in general - don't type in the "event" stubs for a button - double click on the button - it will create + wire it up for you.
Note close, if I flip back to mark-up, the button has become this:
<asp:Button ID="cmdSearch" runat="server" Text="Search" OnClick="cmdSearch_Click" />

Get data from from repeater via Request.Form to another page

I have a simple repeater to list textbox.
try.aspx
<form id="form1" runat="server" action="try_send.aspx" method="get">
<div>
<asp:Repeater ID="ClRpt" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Kod" runat="server" Text='<%#Eval("KOD") %>'></asp:Label>
<asp:TextBox ID="Amount" runat="server"></asp:TextBox>
<asp:Button ID="ButtonClick" CssClass="bt" runat="server" Text="SEPETE EKLE" Width="100%" UseSubmitBehavior="false" />
</ItemTemplate>
</asp:Repeater>
</div>
</form>
try.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
string Firma = Session["FirmaID"].ToString();
string Pryt = "01";
string GRID = "KATALOG";
Page.Title = GRID + " ÜRÜN LİSTESİ";
string SQLGrup = "SQL Here";
SqlCommand rsCl = new SqlCommand(SQLGrup, bag.Bagla());
SqlDataReader ClOku = rsCl.ExecuteReader();
ClRpt.DataSource = ClOku;
ClRpt.DataBind();
ClOku.Close();
}
I want to send textbox value named Amount to try_send.aspx file
try_send.aspx:
<body>
<asp:Label ID="Amount" runat="server" Text="Label"></asp:Label>
</body>
try_send.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
decimal Amnt = Convert.ToDecimal(Request.Form["Amount"]);
Amount.Text = Amnt.ToString();
}
Amount is null when I send the form.
Thanks...
In try.aspx, you just show a bunch of information in your Repeater.
You don't have a button to submit the action.
<form id="form1" runat="server">
<asp:Repeater ID="ClRpt" runat="server">
//content
</asp:Repeater>
<asp:Button Id="xx" runat="server" OnClick="xx_OnClick"/>
</form>
Then, you redirect and pass the amount you want in the event click
public void xx_Onclick(object sender, EventArgs e)
{
//redirect to try_send with the value amount
}

Repeater Control, Insert

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();
}
}

ASP.Net c#, Repeater Itemcommand. I don't delete data

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"

Search Button on Master Page Returns to Existing GridView on Separate Search Page

I'm looking to make a master page search return results to a GridView on another page, which also has a search button. I'd be grateful for any pointers on how to do this....
From Search Page .cs file. Following is Code on Search page and it's .cs page, search page button code, and master page search button code:
From Search Page .cs file:
if (IsPostBack)
{
OdbcConnection MyConnection = new OdbcConnection("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost; DATABASE=petsdat; UID=root; PASSWORD=; OPTION=3");
MyConnection.Open();
OdbcCommand MyCommand = MyConnection.CreateCommand();
MyCommand.CommandText = "SELECT * FROM pets WHERE species like '%" + txtSearch.Text + "%'";
OdbcDataReader MyDataReader = MyCommand.ExecuteReader();
grdSearch.DataSource = MyDataReader;
grdSearch.DataBind();
MyConnection.Close();
}
From Search Page:
<form id="form2" >
<div>
<h1>Search for Pets</h1>
<hr />
<asp:Label runat="server" ID="lblSearch" Text="Search"></asp:Label>
<asp:TextBox runat="server" ID="txtSearch"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtSearch" ErrorMessage="Try Again"></asp:RequiredFieldValidator>
<asp:Button runat="server" ID="btnSubmit" PostBackUrl="~/Search.aspx" Text="Submit" />
<br />
<br />
<br />
<asp:GridView runat="server" ID="grdSearch" BorderColor="#CC6600"
BorderStyle="Solid" BorderWidth="1px" Font-Names="Arial" Font-Size="Medium"
GridLines="Both" HorizontalAlign="Left" Width="600px"></asp:GridView>
<br />
<br />
<br />
<br />
<br />
<br />
</div>
</form>
</asp:Content>
Master Page Search Submit Button Code:
<asp:TextBox ID="Search1" runat="server" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit" PostBackUrl="~/Search.aspx" />
On Button1 Click event you can set the value of Search1 (TextBox) in QueryString & the do a redirect to your Search Page.
Eg.:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("~/Search.aspx?SearchText=" + Search1.Text);
}
Also, you have to modify the Search Page Code:
string searchText = "";
if(Request.QueryString["SearchText"] != null)
searchText = Request.QueryString["SearchText"];
MyCommand.CommandText =
"SELECT * FROM pets WHERE species like '%" + searchText + "%'";

Categories

Resources