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"
Related
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();
}
}
So I have a c# page with a GridView. For some reason, after adding the label and the template for editing, when I click the update button in the edit column, the GridView disappears and none of the records get changed. I know I need to databind the values in the edit box once the user clicks update but I'm not sure how. Can anyone give any suggestions?
Here is my code.
public partial class CMSWebParts_Custom_Development_DevWebPart :
CMSAbstractWebPart
{
public string paramId;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["RefUrl"] = Request.UrlReferrer.ToString();
}
string urlString = Request.UrlReferrer.ToString();
paramId = HttpUtility.ParseQueryString(urlString).Get("Theid");
DispatchNumberLabel.Text = getDispatchNumber();
//TerminalLabel.Text = getTerminal();
DispatchInfoIdLabel.Text = getDispatchInfoId();
DriverNameLabel.Text = getDriverName();
}
protected string getDispatchInfoId()
{
string result = DriverDropDownList.SelectedValue;
return result;
}
protected string getDispatchNumber()
{
string result = paramId;
return result;
}
protected string getTerminal()
{
string result;
string connectionString = "";
using (var con = new SqlConnection(connectionString))
{
var sql = "Select Terminal from Form_IntranetSharpTransit_DispatchInfo where ([Dispatch] = #Dispatch)";
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#Dispatch", getDispatchNumber());
con.Open();
result = (string)cmd.ExecuteScalar();
}
}
return result;
}
protected string getDriverName()
{
string result;
string connectionString = "";
using (var con = new SqlConnection(connectionString))
{
var sql = "Select Driver from Form_IntranetSharpTransit_DispatchInfo WHERE ([DispatchInfoID] = #DispatchInfoId)";
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#DispatchInfoId", getDispatchInfoId());
con.Open();
result = (string)cmd.ExecuteScalar();
}
}
return result;
}
}
And here is my code behind.
<%# Control Language="C#" AutoEventWireup="true"
CodeFile="~/CMSWebParts/Custom/Development/DevWebPart.ascx.cs"
Inherits="CMSWebParts_Custom_Development_DevWebPart" %>
<%--<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
}
</script>--%>Dispatch Number:
<asp:Label ID="DispatchNumberLabel" runat="server"></asp:Label>
<p>
Terminal:
<asp:Label ID="TerminalLabel" runat="server"></asp:Label>
</p>
<p>
Current
Dispatch Info ID:
<asp:Label ID="DispatchInfoIdLabel" runat="server"></asp:Label>
</p>
<p>
Driver Name:
<asp:Label ID="DriverNameLabel" runat="server"></asp:Label>
</p>
<asp:DropDownList ID="DriverDropDownList" runat="server" AutoPostBack="True"
DataSourceID="DriverListData" DataTextField="Select Driver"
DataValueField="Column1">
</asp:DropDownList>
<asp:SqlDataSource ID="DriverListData" runat="server" ConnectionString="<%$
ConnectionStrings:ConnectionString %>" ProviderName="<%$
ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="Select
'', 'Select Driver' as 'Select Driver'
from Form_IntranetSharpTransit_DispatchInfo
Union
SELECT DispatchInfoID, Driver + ' - ' + CAST(DispatchInfoID AS
varchar(50)) AS Expr1
FROM Form_IntranetSharpTransit_DispatchInfo
WHERE (Dispatch = ?) AND (DaysOff NOT LIKE '%' + (SELECT DispatchDay
FROM Form_IntranetSharpTransit_DailyDispatch Where DailydispatchID = ?) +
'%') AND (Status LIKE 'Available')">
<SelectParameters>
<asp:QueryStringParameter Name="?" QueryStringField="Theid" />
<asp:QueryStringParameter Name="?" QueryStringField="Theid" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AutoGenerateEditButton="True" DataSourceID="Store1Data" EditIndex="0"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Store 1:">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"
OnTextChanged="TextBox1_TextChanged" Text='<%# Bind("[Store Number]") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("[Store
Number]") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="Store1Data" runat="server" ConnectionString="<%$
ConnectionStrings:ConnectionString %>" ProviderName="<%$
ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT
(SELECT Store
FROM Form_IntranetSharpTransit_TourPlan
WHERE (TourPlanID =
Form_IntranetSharpTransit_DispatchInfo_1.Store1)) AS 'Store Number',
Location1, Pro1, Store1Export
FROM Form_IntranetSharpTransit_DispatchInfo AS
Form_IntranetSharpTransit_DispatchInfo_1
WHERE (DispatchInfoID = ?)">
<SelectParameters>
<asp:ControlParameter ControlID="DriverDropDownList" Name="?"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
All I want is to display the table with an edit button. When the edit button is clicked, I want the label in table to become an edit box (as my template shows). After the user has modified the edit box, they can then click the update button, committing the change to the database and refreshing the table to show the changed values.
This seems extremely simple but I have been struggling with it for about 3 months now.
Please help.
Here's a minimal, yet working, example of what you are trying to achieve.
Though I must admit, the Microsoft Documentation came in pretty handy for this snippet.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UpdateGridViewOnPostBack_45921943.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="dgv1" AutoGenerateEditButton="true" OnRowEditing="dgv1_RowEditing" OnRowUpdating="dgv1_RowUpdating">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="gvCol1Label" Text='<%#Bind("field1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="gvCol1Txtbx" Text='<%# Bind("field1") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web.UI.WebControls;
using System.Collections.ObjectModel;
namespace UpdateGridViewOnPostBack_45921943
{
public partial class Default : System.Web.UI.Page
{
static ObservableCollection<dgvEntry> dgv1Source;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Not a postback
dgv1Source = new ObservableCollection<dgvEntry>();
dgv1Source.Add(new dgvEntry { field1 = "the field coming from the data source" });
initializeDGV(IsPostBack);
}
else
{
//is a postback
if (dgv1Source == null)
{
dgv1Source = new ObservableCollection<dgvEntry>();
}
initializeDGV(IsPostBack);
}
}
private void initializeDGV(bool isPostback)
{
dgv1.DataSource = dgv1Source;
dgv1.AutoGenerateColumns = false;
if (!isPostback)
{
dgv1.DataBind();
}
}
protected void dgv1_RowEditing(object sender, GridViewEditEventArgs e)
{
dgv1.EditIndex = e.NewEditIndex;
dgv1.DataBind();
}
protected void dgv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = dgv1.Rows[e.RowIndex];
dgv1Source[e.RowIndex].field1 = ((TextBox)row.Cells[1].Controls[1]).Text;
dgv1.EditIndex = -1;
dgv1.DataBind();
}
}
public class dgvEntry
{
public string field1 { get; set; }
//public string field2 { get; set; }
//public string field3 { get; set; }
}
}
I'm trying to get the value from the selected item when I click a button.
Here is my code:
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%">
<ItemTemplate>
<p class="own"><asp:Image ID="Image1" runat="server" ImageUrl='<%# "GetImageDatafromDB.aspx?id=" + System.Convert.ToString(Eval("ID")) %>' Width="230" Height="250"/>
<br />
<span class="own1" style="width:230px;"><br /><asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>' Font-Bold="True" Font-Size="1.2em" ForeColor="White"/>
<br />
<asp:Label ID="Label5" runat="server" Text="Direktor :" style="color:#06D85F; float:left"></asp:Label><asp:Label ID="Label2" runat="server" CssClass="InFo" Text='<%# Eval("fattare") %>' Font-Italic="true"/>
<br />
<asp:Label ID="Label4" runat="server" Text="Year : " style="color:#06D85F; float:left;"></asp:Label><asp:Label ID="Label3" CssClass="InFo" runat="server" Text=' <%# (Eval("Ar")) %>' />
</br>
<asp:Button ID="Button1" runat="server" Text="Visa" CommandName="ButtonClick"/>
</span>
<asp:Label ID="Label6" runat="server" Visible="false" Text='<%# Eval("Name") %>'></asp:Label>
</p>
</ItemTemplate>
</asp:DataList>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["Hemsida"].ConnectionString;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connectionString);
using (conn)
{
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Movies", conn);
ad.Fill(dt);
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
Label myTempLabel = (Label)item.FindControl("Label6");
myTempLabel.Visible = true;
}
}
When I click the button, I get all of the names of all of the items, but I only want to get the name of the selected item.
On the ItemCommand event of DataList1, paste the following code:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
DataList1.SelectedIndex = e.Item.ItemIndex;
myTempLabel.Text = "You selected: " + ((Label)DataList1.SelectedItem.FindControl("Label1")).Text;
myTempLabel.Visible = true;
}
I believe you need to use SelectedItem.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.selecteditem(v=vs.110).aspx
Something like this:
protected void Button1_Click(object sender, EventArgs e)
{
if (DataList1.SelectedItem != null)
{
Label myTempLabel = (Label)DataList1.SelectedItem.FindControl("Label6");
myTempLabel.Visible = true;
}
}
Try changing this:
<asp:Button ID="Button1" runat="server" Text="Visa" CommandName="ButtonClick"/>
to This:
<asp:Button ID="Button1" runat="server" Text="Visa" OnClick="Button1_Click"
/>
Another alternative is to remove the code in the button and handle it on the Item_Command:
//Add item command to DataList
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%" OnItemCommand="Item_Command">
void Item_Command(Object sender, DataListCommandEventArgs e)
{
// Set the SelectedIndex property to select an item in the DataList.
ItemsList.SelectedIndex = e.Item.ItemIndex;
//Get the selected Item
DataListItem selectedItem = DataList1.DataKeys[DataListList1.SelectedIndex];
//Get the label control
Label myTempLabel = (Label)selectedItem.FindControl("Label6");
myTempLabel.Visible = true;
// Not sure if this is needed.
//ItemsList.DataSource = CreateDataSource();
//ItemsList.DataBind();
}
If the textbox that gets the value is outside your update panel then try this:
if (e.CommandName == "selectitem")
{
DataList1.SelectedIndex = e.Item.ItemIndex;
TextBox2.Text = Label)DataList1.SelectedItem.FindControl("Label1")).Text;
}
If the textbox that gets the value is inside your update panel then try this
if (e.CommandName == "selectitem")
((Label)e.Item.FindControl("Label1")).Text = e.CommandArgument.ToString();
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)
}
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 + "%'";