I have a dropdown menu bounded with values from the db on form load. I wanted to use the dropdown as a filter to update a datagrid using an updatepanel, which I managed to get working. I'm binding the datagrid in form load and on selected index changed as shown. I also want to use the same dropdown to update a formview using the DataValueField, which for some reason isn't working. Could the reason be that I'm using two different updatepanels and the same asynchpostbacktrigger? Where should I be binding data to the formview? Your input would be greatly appreciated! Thanks in advance...
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
SqlCommand cmd3 = new SqlCommand("SELECT c.Email As CompanyEmail, c.Telephone AS Telephone, m.Email AS AdminEmail, m.FirstName + ' ' + m.LastName AS CompanyAdmin FROM Company c, Member m WHERE m.CompanyID = c.CompanyID AND m.CompanyID = '" + company_id + "' AND m.CompanyRole = 'Admin'", conn);
SqlCommand cmd = new SqlCommand("SELECT CompanyName, CompanyID FROM Company ORDER BY CompanyName", conn);
SqlCommand cmd2 = new SqlCommand("SELECT p.ProjectName AS ProjectName, p.ProjectID, p.CompanyID, p.Status AS Status FROM Project p, Company c WHERE p.CompanyID = c.CompanyID AND c.CompanyID = '" + company_id + "' ORDER BY ProjectName", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (!Page.IsPostBack)
{
company_list.DataSource = ds;
company_list.DataTextField = "CompanyName";
company_list.DataValueField = "CompanyID";
company_list.DataBind();
company_list.Items.Insert(0, new System.Web.UI.WebControls.ListItem("-- Please Select Company --"));
}
//cmd2.Connection.Open();
cmd2.CommandType = CommandType.Text;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd2);
DataSet ds2 = new DataSet();
sqlAdapter.Fill(ds2);
Gridview1.DataSource = ds2;
Gridview1.DataBind();
FormView1.DataSource = cmd3.ExecuteReader();
FormView1.DataBind();
conn.Close();
//}
//cmd2.Connection.Close();
//cmd2.Connection.Dispose();
}
}
protected void company_list_SelectedIndexChanged(object sender, EventArgs e)
{
company_id = company_list.SelectedValue;
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
SqlCommand cmd2 = new SqlCommand("SELECT p.ProjectName AS ProjectName, p.ProjectID, p.CompanyID, p.Status AS Status FROM Project p, Company c WHERE p.CompanyID = c.CompanyID AND c.CompanyID = '" + company_id + "' ORDER BY ProjectName", conn);
cmd2.CommandType = CommandType.Text;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd2);
DataSet ds2 = new DataSet();
sqlAdapter.Fill(ds2);
Gridview1.DataSource = ds2;
Gridview1.DataBind();
SqlCommand cmd = new SqlCommand("SELECT c.Email As CompanyEmail, c.Telephone AS Telephone, m.Email AS AdminEmail, m.FirstName + ' ' + m.LastName AS CompanyAdmin FROM Company c, Member m WHERE m.CompanyID = c.CompanyID AND m.CompanyID = '" + company_id + "' AND m.CompanyRole = 'Admin'", conn);
cmd.CommandType = CommandType.Text;
FormView1.DataSource = cmd.ExecuteReader();
FormView1.DataBind();
conn.Close();
}
ASP.NET:
<div style="float:left;">
<table>
<tr>
<td class="style1">Select Company:</td>
<td><asp:DropDownList ID="company_list" runat="server"
onselectedindexchanged="company_list_SelectedIndexChanged" width="185" AutoPostBack="true" /></td>
</tr>
<tr>
<td colspan="2" align="right"> </td>
</tr>
</table>
<asp:UpdatePanel ID="UpdateInfo" runat="server">
<ContentTemplate>
<asp:FormView ID="FormView1" runat="server">
<ItemTemplate>
<table>
<tr>
<td>Company Admin:</td>
<td><asp:TextBox Text='<%# Eval("Email") %>' CssClass="input input1" ID="co_admin" width="150" runat="server" ReadOnly="True" /></td>
</tr>
<tr>
<td>Admin Email:</td>
<td><asp:TextBox Text='<%# Eval("AdminEmail") %>' CssClass="input input1" ID="ad_email" width="150" runat="server" ReadOnly="True" /></td>
</tr>
<tr>
<td>Company Email:</td>
<td><asp:TextBox Text='<%# Eval("CompanyEmail") %>' CssClass="input input1" ID="co_email" width="150" runat="server" ReadOnly="True" /></td>
</tr>
<tr>
<td>Telephone:</td>
<td><asp:TextBox Text='<%# Eval("Telephone") %>' CssClass="input input1" ID="telephone" width="150" runat="server" ReadOnly="True" /></td>
</tr>
<tr>
<td></td>
<td><asp:Button CssClass="button_style" width="170" ID="export" Text="EXPORT TO EXCEL" runat="server" /></td>
</tr>
</table>
</ItemTemplate>
</asp:FormView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="company_list" />
</Triggers>
</asp:UpdatePanel>
</div>
<center>
<asp:UpdatePanel ID="UpdateGrid" runat="server">
<ContentTemplate>
<asp:gridview ID="Gridview1" runat="server" ShowFooter="True"
AutoGenerateColumns="False" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="Project Name">
<ItemTemplate>
<asp:TextBox Text='<%# Eval("ProjectName") %>' CssClass="input input1" ID="project_name" width="150" runat="server" ReadOnly="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemStyle Width="150" />
<ItemTemplate>
<center><asp:Image ImageUrl='<%# GetStatusImage(Eval("Status").ToString()) %>' ID="status" runat="server"/></center>
</ItemTemplate>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="company_list" />
</Triggers>
</asp:UpdatePanel>
I tried to recreate your scenario with this following code. (And it works)
protected void Page_Load(object sender, EventArgs e)
{
var foos = GetFoos();
Gridview1.DataSource = foos;
Gridview1.DataBind();
DetailsView1.DataSource = foos;
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
DetailsView1.DataBind();
DropDownList1.Items.AddRange(foos.Select(f => new ListItem(f.Name, f.Name)).ToArray());
DropDownList1.Items.Insert(0,new ListItem("-Select-"));
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedValue = DropDownList1.SelectedValue;
var foos = GetFoos().Where(f => f.Name == selectedValue);
Gridview1.DataSource = foos;
Gridview1.DataBind();
DetailsView1.DataSource = foos;
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
DetailsView1.DataBind();
}
static List<Foo> GetFoos()
{
var list = new List<Foo>();
for(int i=0;i<10;i++)
{
list.Add(new Foo {City = "City" + i, Name = "Name" + i});
}
return list;
}
class Foo
{
public string Name { get; set; }
public string City { get; set; }
}
and here's the markup
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView runat="server" ID="Gridview1">
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px">
</asp:DetailsView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" />
</Triggers>
</asp:UpdatePanel>
</asp:Content>
So, it's something with the formview you have. Can you switch to using DetailsView ?
Related
Hi I have used gridview to create a table.
Is there a way to implement edit and delete.
I have done it in PHP before. The method I would like to use is create two more columns in the table with edit and delete buttons on each row. Then when the buttons are click it passes the 'id' through the URL and able to edit or delete. Not really sure how to do this in asp.net webforms. Below is my code for the table. Thank you.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Surgery" DataField="surgery" />
<asp:BoundField HeaderText="PatientID" DataField="patientID" />
<asp:BoundField HeaderText="Location" DataField="location" />
</Columns>
SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
The GridView supports those operations. You can add a CommandField which will contain the command buttons or LinkButtons (you can choose the type of button and assign the text of each button). The patientID field should be included in the DataKeyNames property of the GridView, in order to retrieve it when the time comes to update or delete the record in the database.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="patientID"
OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" >
<Columns>
<asp:CommandField ShowEditButton="true" ShowCancelButton="true" ShowDeleteButton="true" />
<asp:BoundField HeaderText="Surgery" DataField="surgery" />
...
</Columns>
You will then need to handle a few events in code-behind:
// The RowEditing event is called when data editing has been requested by the user
// The EditIndex property should be set to the row index to enter edit mode
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
// The RowCancelingEdit event is called when editing is canceled by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
// The RowUpdating event is called when the Update command is selected by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int patientID = (int)e.Keys["patientID"]
string surgery = (string)e.NewValues["surgery"];
string location = (string)e.NewValues["location"];
// Update here the database record for the selected patientID
GridView1.EditIndex = -1;
BindData();
}
// The RowDeleting event is called when the Delete command is selected by the user
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int patientID = (int)e.Keys["patientID"]
// Delete here the database record for the selected patientID
BindData();
}
Since the data must be bound to the GridView at the end of each of those event handlers, you can do it in a BindData utility function, which should also be called when the page loads initially:
private void BindData()
{
SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
And Store Procedure is:
USE [DemoProjet]
GO
/****** Object: StoredProcedure [dbo].[Customers_CRUD] Script Date: 11-Jan-17 2:57:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Customers_CRUD]
#Action VARCHAR(10)
,#BId INT = NULL
,#Username VARCHAR(50) = NULL
,#Provincename VARCHAR(50) = NULL
,#Cityname VARCHAR(50) = NULL
,#Number VARCHAR(50) = NULL
,#Name VARCHAR(50) = NULL
,#ContentType VARCHAR(50) = NULL
,#Data VARBINARY(MAX) = NULL
AS
BEGIN
SET NOCOUNT ON;
--SELECT
IF #Action = 'SELECT'
BEGIN
SELECT BId , Username,Provincename,Cityname,Number,Name,ContentType, Data
FROM tblbooking
END
--INSERT
IF #Action = 'INSERT'
BEGIN
INSERT INTO tblbooking(Username,Provincename,Cityname,Number,Name,ContentType, Data)
VALUES (#Username ,#Provincename ,#Cityname ,#Number ,#Name ,#ContentType ,#Data)
END
--UPDATE
IF #Action = 'UPDATE'
BEGIN
UPDATE tblbooking
SET Username = #Username,Provincename = #Provincename,Cityname = #Cityname,Number = #Number,Name = #Name,ContentType = #ContentType,Data = #Data
WHERE BId = #BId
END
--DELETE
IF #Action = 'DELETE'
BEGIN
DELETE FROM tblbooking
WHERE BId = #BId
END
END
GO
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;
namespace FinalYearProject
{
public partial class MBooking : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void Insert(object sender, EventArgs e)
{
string Username = txtUsername.Text;
string Provincename = txtProvinceName.Text;
string Cityname = txtCityname.Text;
string Number = txtNumber.Text;
string Name = txtName.Text;
string ContentType = txtContentType.Text;
string Data = txtData.Text;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "INSERT");
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Provincename ", Provincename);
cmd.Parameters.AddWithValue("#Cityname", Cityname);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#ContentType", ContentType);
//cmd.Parameters.AddWithValue("#Data", Data);
cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnRowCancelingEdit(object sender, EventArgs e)
{
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string Username = (row.FindControl("txtUserName") as TextBox).Text;
string Provincename = (row.FindControl("txtProvincename") as TextBox).Text;
string Cityname = (row.FindControl("txtCityname") as TextBox).Text;
string Number = (row.FindControl("txtNumber") as TextBox).Text;
string Name = (row.FindControl("txtName") as TextBox).Text;
string ContentType = (row.FindControl("txtContentType") as TextBox).Text;
string Data = (row.FindControl("txtData") as TextBox).Text;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "UPDATE");
cmd.Parameters.AddWithValue("#BId", BId);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Provincename ", Provincename);
cmd.Parameters.AddWithValue("#Cityname", Cityname);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#ContentType",ContentType) ;
cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
//cmd.Parameters.AddWithValue("#ContentType", SqlDbType.VarBinary, -1);
//cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary, -1);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
//if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
//{
// (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
//}
}
protected void DownloadFile(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Name, Data, ContentType from tblbooking where BId=#BId";
cmd.Parameters.AddWithValue("#BId",id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "DELETE");
cmd.Parameters.AddWithValue("#BId", BId);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
}
}
And Aspx page is:
<%# Page Title="" Language="C#" MasterPageFile="~/admin.Master" AutoEventWireup="true" CodeBehind="MBooking.aspx.cs" Inherits="FinalYearProject.MBooking" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<style type="text/css">
<%-- body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
border-collapse: collapse;
background-color: #fff;
}
table th
{
background-color: #B8DBFD;
color: #333;
font-weight: bold;
}
table th, table td
{ background-color: #B8DBFD;
padding: 5px;
border: 1px solid #ccc;
}
table, table table td
{
border: 3px solid #ccc;
}
--%>
.style1
{
width: 184px;
}
</style>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
OnPageIndexChanging="OnPageIndexChanging" PageSize="6" DataKeyNames="BId"
OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting"
EmptyDataText="No records has been added."
Style="margin:20px 0px 0px 25px;" BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4" Height="250px"
Width="1035px" >
<Columns>
<asp:TemplateField HeaderText="Username" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblUsername" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUsername" style = "Width:100px;" runat="server" Text='<%# Eval("Username") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProvinceName" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblProvinceName" runat="server" Text='<%# Eval("Provincename") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProvinceName" style = "Width:100px;" runat="server" Text='<%# Eval("Provincename") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="CityName" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblCityname" runat="server" Text='<%# Eval("Cityname") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCityname" style = "Width:100px;" runat="server" Text='<%# Eval("Cityname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Number" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblNumber" runat="server" Text='<%# Eval("Number") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNumber" style = "Width:100px;" runat="server" Text='<%# Eval("Number") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Name" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" style = "Width:100px;" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="ContentType" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblContentType" runat="server" Text='<%# Eval("ContentType") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtContentType" style = "Width:100px;" runat="server" Text='<%# Eval("ContentType") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Data" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblData" runat="server" Text='<%# Eval("Data") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtData" style = "Width:100px;" runat="server" Text='<%# Eval("Data") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField> <ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
CommandArgument='<%# Eval("BId") %>'></asp:LinkButton>
</ItemTemplate></asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true"
ItemStyle-Width="100" >
<ItemStyle Width="100px"></ItemStyle>
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Center"
Font-Bold="True" Font-Italic="True" Font-Underline="True" Width="20px" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
<br />
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse; margin:10px 0px 0px 25px;">
<tr>
<td style="width: 100px; background-color:#003399; color:#CCCCFF;">
<b> Username:</b><br />
<asp:TextBox ID="txtUsername" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Provincename:</b><br />
<asp:TextBox ID="txtProvinceName" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b>Cityname:</b><br />
<asp:TextBox ID="txtCityname" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Number:</b><br />
<asp:TextBox ID="txtNumber" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Name:</b><br />
<asp:TextBox ID="txtName" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> ContentType:</b><br />
<asp:TextBox ID="txtContentType" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b>Data:</b><br />
<asp:TextBox ID="txtData" runat="server" Width="120" />
</td>
<td style="background-color:#003399; color:#CCCCFF;" class="style1">
<asp:Button ID="btnAdd" runat="server" CssClass="btn btn-info" Text="Add"
OnClick="Insert" Width="187px" />
</td>
</tr>
</table>
</asp:Content>
I have this repeater
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div class="detail">
<asp:Label ID="LabelID" runat="server" Visible="true" Text='<%#DataBinder.Eval(Container.DataItem, "Id") %>'>'></asp:Label><br />
<b>Namn:</b> <asp:Label ID="Label1" runat="server" Text='<%#Eval("Namn") %>'>'></asp:Label> <br />
<b>Address</b> <asp:Label ID="Label3" runat="server" Text='<%#Eval("Adress") %>'></asp:Label><br />
<b>Telefonnummer</b> <asp:Label ID="Label4" runat="server" Text='<%#Eval("Telefonnummer") %>'></asp:Label><br />
<b>Mailaddres</b> <asp:Label ID="Label5" runat="server" Text='<%#Eval("Epost-address") %>'></asp:Label><br />
<b>Meddelande:</b> <asp:Label ID="Label6" runat="server" Text='<%#Eval("Kommentar") %>'></asp:Label><br />
<asp:LinkButton ID="lnkDelete" runat="server" CommandArgument='<%#Eval("Id") %>' CommandName="Delete" onclientclick="return confirm('Are you sure you want to delete?')">Delete</asp:LinkButton>
</div>
</ItemTemplate>
</asp:Repeater>
And this is the code behind it:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeater();
}
}
protected void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete") {
int id = Convert.ToInt32(e.CommandArgument);
deleteKlag(id);
}
}
void deleteKlag(int id)
{
SqlConnection sqlcn = new SqlConnection(#"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database.mdf;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework");
SqlCommand sqlcm = new SqlCommand("DELETE FROM [Table] WHERE [Id] = #Id", sqlcn);
sqlcm.Parameters.AddWithValue("#Id", id);
if (sqlcn.State == ConnectionState.Closed)
{
sqlcn.Open();
}
sqlcm.ExecuteNonQuery();
sqlcn.Close();
BindRepeater();
}
protected void BindRepeater()
{
SqlConnection con = new SqlConnection(#"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database.mdf;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework");
string command = "Select * from [Table]";
SqlCommand cmd = new SqlCommand(command, con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
Repeater1.DataSource = cmd.ExecuteReader();
Repeater1.DataBind();
}
It shows all the items in the database fine, but when I press the "Delete" button nothing happens. I have tried many different variations but they all end up doing nothing. Any ideas?
Ahhhhh I forgot to put
OnItemCommand="rpt_ItemCommand"
on my Repeater tag
I have created a gridview, for the user to add/edit and remove products. (not actually deleting but declaring it discontinued on the database)
I am getting the following exception:
An exception of type 'System.FormatException' occurred in mscorlib.dll
but was not handled in user code
My markup is as follows:
<%# Page Title="" Language="C#" MasterPageFile="~/Admin/AdminMaster.master" AutoEventWireup="true" CodeFile="addProduct.aspx.cs" Inherits="Admin_addProduct" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightCol" runat="Server">
<h1>Products</h1>
<asp:Label ID="lblProdGrd" runat="server"></asp:Label>
<asp:SqlDataSource ID="lstCatSrc" runat="server" ConnectionString='<%$ ConnectionStrings:bncConn %>' SelectCommand="SELECT CategoryName, CategoryId FROM ProductDetails.Category"></asp:SqlDataSource>
<asp:SqlDataSource ID="lstSubCatSrc" runat="server" ConnectionString='<%$ ConnectionStrings:bncConn %>' SelectCommand="SELECT ProductType, ProductTypeId FROM ProductDetails.ProductType"></asp:SqlDataSource>
<asp:SqlDataSource ID="lstImgSrc" runat="server" ConnectionString='<%$ ConnectionStrings:bncConn %>' SelectCommand="SELECT ImageName, ImageId, ImagePath FROM ProductDetails.ProductImages"></asp:SqlDataSource>
<asp:GridView
ID="grdProds"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdProds_PageIndexChanging"
OnRowCancelingEdit="grdProds_RowCancelingEdit"
OnRowCommand="grdProds_RowCommand"
OnRowEditing="grdProds_RowEditing"
OnRowUpdating="grdProds_RowUpdating"
onrowdeleting="grdProds_RowDeleting">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" FooterText="Product ID" HeaderText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" Text='<%# Eval("ProductId") %>' runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblAdd" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Name" HeaderText="Product Name" FooterText="ProductName">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("ProductName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Description" AccessibleHeaderText="Product description" FooterText="Product Description">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Text='<%# Eval("Description")%>' TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDescription" runat="server" TextMode="MultiLine"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Price" AccessibleHeaderText="Product Price" FooterText="Product Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("Price") %>' ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPrice" runat="server" Text='<%# Bind("Price") %>' TextMode="Number"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddPrice" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCat" runat="server" Text='<%# Eval("CategoryName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstCatEdit" runat="server" DataSourceID="lstCatSrc" DataTextField="CategoryName" DataValueField="CategoryId" AppendDataBoundItems="True">
<asp:ListItem Text="--(Select a category)--" Value="NULL"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstCat" runat="server" DataSourceID="lstCatSrc" DataTextField="CategoryName" DataValueField="CategoryId" AppendDataBoundItems="True">
<asp:ListItem Text="--(Select a category)--" Value="NULL"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub-Category" AccessibleHeaderText="Sub-Category" FooterText="Sub-Category">
<ItemTemplate>
<asp:Label ID="lblSubCat" runat="server" Text='<%# Eval("ProductType") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstSubCat" runat="server" DataSourceID="lstSubCatSrc" DataTextField="ProductType" DataValueField="ProductTypeId"></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddSubCat" runat="server" DataSourceID="lstSubCatSrc" DataTextField="ProductType" DataValueField="ProductTypeId"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Image" AccessibleHeaderText="Product Image" FooterText="Product Image">
<ItemTemplate>
<asp:Image ID="imgProd" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstProdImg" runat="server" DataSourceID="lstImgSrc" DataTextField="ImageName" DataValueField="ImageId"></asp:DropDownList>
<asp:Image ID="imgProdEdit" runat="server" Height="250" Width="250" />
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdImg" runat="server" DataSourceID="lstImgSrc" DataTextField="ImageName" DataValueField="ImageId"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item in stock" AccessibleHeaderText="Item in stock" FooterText="Item in stock">
<ItemTemplate>
<asp:CheckBox ID="chkInStock" runat="server" Checked='<%# Eval("InStock") %>' Enabled="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkInStockEdit" runat="server" Checked='<%# Eval("InStock") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkInStockAdd" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pre-Designed" AccessibleHeaderText="Pre-designed" FooterText="Pre-Designed">
<ItemTemplate>
<asp:CheckBox ID="chkPrePrinted" runat="server" Checked='<%# Eval("PrePrinted") %>' Enabled="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkPrePrintedEdit" runat="server" Checked='<%# Eval("PrePrinted") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkAddPrePrinted" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to declare this product Discontinued?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
My code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data.Entity;
using BillyNicClothingModel;
public partial class Admin_addProduct : System.Web.UI.Page
{
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
string CatLst;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Display";
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds, "Products");
grdProds.DataSource = ds;
grdProds.DataBind();
}
catch (Exception err)
{
lblProdGrd.Text = err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdProds.PageIndex = e.NewPageIndex;
BindGrid();
}
protected void grdProds_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdProds.EditIndex = -1;
BindGrid();
}
protected void grdProds_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
TextBox txtName = (TextBox)grdProds.FooterRow.FindControl("txtAddname");
TextBox txtDescription = (TextBox)grdProds.FooterRow.FindControl("txtAddDescription");
TextBox txtPrice = (TextBox)grdProds.FooterRow.FindControl("txtAddPrice");
DropDownList lstCatEdit = (DropDownList)grdProds.FooterRow.FindControl("lstCat");
DropDownList lstSubCat = (DropDownList)grdProds.FooterRow.FindControl("lstAddSubCat");
DropDownList lstImageProd = (DropDownList)grdProds.FooterRow.FindControl("lstAddProdImg");
CheckBox chkInStockEdit = (CheckBox)grdProds.FooterRow.FindControl("chkInStockAdd");
CheckBox chkPrePrinted = (CheckBox)grdProds.FooterRow.FindControl("chkAddPrePinted");
string ProductName, Description;
int Category, Image;
bool InStock, Preprinted;
decimal Price;
byte SubCat;
ProductName = txtName.Text;
Description = txtDescription.Text;
Price = Decimal.Parse(txtPrice.Text);
Category = int.Parse(lstCatEdit.SelectedValue);
SubCat = byte.Parse(lstSubCat.SelectedValue);
Image = int.Parse(lstImageProd.SelectedValue);
InStock = chkInStockEdit.Checked;
Preprinted = chkPrePrinted.Checked;
AddProduct(ProductName, Description, Price, Category, SubCat, Image, InStock, Preprinted);
grdProds.EditIndex = -1;
BindGrid();
}
}
protected void AddProduct(string ProductName, string Description, decimal Price, int Category, int SubCat,
int Image, bool InStock, bool Preprinted)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Add";
cmd.Parameters.Add(new SqlParameter("#ProductName", SqlDbType.VarChar, 50));
cmd.Parameters["#ProductName"].Value = ProductName;
cmd.Parameters.Add(new SqlParameter("#Description", Description));
cmd.Parameters["#Description"].Value = Description;
cmd.Parameters.Add(new SqlParameter("#Price", SqlDbType.Money));
cmd.Parameters["#Price"].Value = Price;
cmd.Parameters.Add(new SqlParameter("#Category", SqlDbType.Int));
cmd.Parameters["#Category"].Value = Category;
cmd.Parameters.Add(new SqlParameter("#ProductType", SqlDbType.TinyInt));
cmd.Parameters["#ProductType"].Value = SubCat;
cmd.Parameters.Add(new SqlParameter("#Image", SqlDbType.Int));
cmd.Parameters["#Image"].Value = Image;
cmd.Parameters.Add(new SqlParameter("#InStock", SqlDbType.Bit));
cmd.Parameters["#InStock"].Value = InStock;
cmd.Parameters.Add(new SqlParameter("#PrePrinted", SqlDbType.Bit));
cmd.Parameters["#PrePrinted"].Value = Preprinted;
try {
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text = err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label prId = (Label)grdProds.Rows[e.RowIndex].FindControl("lblProdId");
int pId = Convert.ToInt32(prId.Text);
DeleteProduct(pId);
grdProds.EditIndex = -1;
BindGrid();
}
protected void DeleteProduct(int pId)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Delete";
cmd.Parameters.Add(new SqlParameter("#ProdId", SqlDbType.Int));
cmd.Parameters["#ProdId"].Value = pId;
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_RowEditing(object sender, GridViewEditEventArgs e)
{
grdProds.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grdProds_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label prdId = (Label)grdProds.Rows[e.RowIndex].FindControl("lblProdId");
TextBox Name = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtName");
TextBox Description = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtDescription");
TextBox Price = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtPrice");
DropDownList Category = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstCatEdit");
DropDownList SubCat = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstSubCat");
DropDownList Image = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstProdImg");
CheckBox InStock = (CheckBox)grdProds.Rows[e.RowIndex].FindControl("chkInStockEdit");
CheckBox PrePrinted = (CheckBox)grdProds.Rows[e.RowIndex].FindControl("chkPrePrintedEdit");
int ProdId = Convert.ToInt32(prdId.Text);
string eName = Name.Text;
string eDescription = Description.Text;
Decimal ePrice = Convert.ToDecimal(Price.Text);
int eCat = Convert.ToInt32(Category.SelectedValue);
byte eSCat = Convert.ToByte(SubCat.SelectedValue);
int eImage = Convert.ToInt32(Image.SelectedValue);
bool eInstock = InStock.Checked;
bool ePreprinted = PrePrinted.Checked;
UpdateProduct(ProdId, eName, eDescription, ePrice, eCat, eSCat, eImage, eInstock, ePreprinted);
grdProds.EditIndex = -1;
BindGrid();
}
protected void UpdateProduct(int ProdId, string eName, string eDescription, Decimal ePrice, int eCat, byte eSCat, int eImage, bool eInstock, bool ePreprinted)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#ProdId", SqlDbType.Int));
cmd.Parameters["#ProdId"].Value = Convert.ToInt32(ProdId);
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Update";
cmd.Parameters.Add(new SqlParameter("#ProductName", SqlDbType.VarChar, 50));
cmd.Parameters["#ProductName"].Value = eName;
cmd.Parameters.Add(new SqlParameter("#Description", SqlDbType.VarChar, -1));
cmd.Parameters["#description"].Value = eDescription;
cmd.Parameters.Add(new SqlParameter("#Price", SqlDbType.Money));
cmd.Parameters["#Price"].Value = ePrice;
cmd.Parameters.Add(new SqlParameter("#Category", SqlDbType.Int));
cmd.Parameters["#Category"].Value = eCat;
cmd.Parameters.Add(new SqlParameter("#ProductType", SqlDbType.TinyInt));
cmd.Parameters["#ProductType"].Value = eSCat;
cmd.Parameters.Add(new SqlParameter("#Image", SqlDbType.Int));
cmd.Parameters["#Image"].Value = eImage;
cmd.Parameters.Add(new SqlParameter("#InStock", SqlDbType.Bit));
cmd.Parameters["#InStock"].Value = eInstock;
cmd.Parameters.Add(new SqlParameter("#PrePrinted", SqlDbType.Bit));
cmd.Parameters["#PrePrinted"].Value = ePreprinted;
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}}
My stored procedure:
CREATE PROCEDURE [ProductDetails].[bnc_Products]
-- Add the parameters for the stored procedure here
#ProdId int = 0,
#Category int = 0,
#ProductType tinyint = 0,
#Price money = 0,
#InStock bit = 1,
#ProductName varchar(50) = '',
#Image int = 0,
#Description varchar(max) = '',
#PrePrinted bit = 1,
#Discontinued bit = 0,
#Status varchar(50) = ''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
if (#Status = 'Display')
begin
select p.ProductId,p.ProductName,c.CategoryId,c.CategoryName,
pt.ProductType,pt.ProductTypeId,p.Price,p.InStock,pi.ImagePath,
pi.ImageId,pi.ImageName,p.Description,p.PrePrinted,p.Discontinued
from ProductDetails.Products p
join ProductDetails.Category c on c.CategoryId = p.Category
join ProductDetails.ProductType pt on pt.ProductTypeId = p.ProductType
join ProductDetails.ProductImages pi on pi.ImageId = p.ImageId
where p.Discontinued = 0
end
else if(#Status = 'Update')
begin
update Productdetails.Products
set Category = #Category, ProductType = #ProductType,
Price = #Price, InStock = #InStock, ProductName = #ProductName,
ImageId = #Image, Description = #Description, PrePrinted = #PrePrinted
where ProductId = #ProdId
end
else if(#Status = 'Add')
begin
insert into ProductDetails.Products
(Category,ProductType,Price,InStock,ProductName,ImageId,Description,PrePrinted,Discontinued)
values (#Category,#ProductType,#Price,#InStock,#ProductName,#Image,#Description,#PrePrinted,#Discontinued)
end
else if(#Status = 'Delete')
begin
Update ProductDetails.Products
set Discontinued = #Discontinued
where ProductId = #ProdId
end
END
Also when I try to delete a product, well declare it to be discontinued, nothing seems to happen and if anyone is able to point out where and what is wrong I would be very grateful as I am at a total loss as to what's going on. Sorry if any of this seems a little vague, I'm quite the novice at this, and so am at a complete standstill at the moment. Thank you in advanced to anyone willing to help.
You getting System.FormatException as have opened the following asp:content but have not closed it:
<asp:content id="Content3" contentplaceholderid="RightCol" runat="Server">
So after </asp:GridView> put </asp:content> and delete function will get executed.
I am making an application about article publication. I have 2 tables
"artikulli"
id int Unchecked
tema varchar(250) Checked
abstrakti text
data_publikimit date
path varchar(350)
keywords varchar(350)
kategoria_id int
departamenti_id int
"kategorite"
id int Unchecked
emertimi varchar(350)
I want to display in a dropdown list all values of field "emertimi" and when the user selects one value to save id of that value in table "artikulli".
I have done the following, but I have the problem with syntax because I am using DATALIST.
public partial class AddArticle : System.Web.UI.Page
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
try
{
if (!IsPostBack)
{
Bind();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
public void Bind()
{
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
protected void datalist2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
TextBox txtAbstrakti = e.Item.FindControl("txtAbstrakti") as TextBox;
TextBox txtData = e.Item.FindControl("txtData") as TextBox;
TextBox txtKeywords = e.Item.FindControl("txtKeywords") as TextBox;
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection conn = new SqlConnection(connection);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "Insert into artikulli(tema,abstrakti,data_publikimit,path,keywords,kategoria_id) values (#tema,#abstrakti,#data,#filename,#keywords,#kategoria)";
command.Parameters.Add(new SqlParameter("#tema", txtTema.Text));
command.Parameters.Add(new SqlParameter("#abstrakti", txtAbstrakti.Text));
command.Parameters.Add(new SqlParameter("#data", txtData.Text));
command.Parameters.Add(new SqlParameter("#keywords", txtKeywords.Text));
command.Parameters.Add(new SqlParameter("#kategoria", drpdKategoria.SelectedValue));
FileUpload FileUploadArtikull = (FileUpload)e.Item.FindControl("FileUploadArtikull");
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise se file qe lejohet eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
//add parameters
command.Parameters.AddWithValue("#filename", filename);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni ngarkuar asnje artikull');", true);
}
}
}
AddArtikull.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddArtikull.aspx.cs" Inherits="AddArticle" MasterPageFile="~/MasterPage2.master" %>
<asp:Content ID="content2" ContentPlaceholderID=ContentPlaceHolder2 runat="server">
<asp:DataList ID="datalist2" runat="server"
onitemcommand="datalist2_ItemCommand" >
<FooterTemplate>
<section id="main" class="column" runat="server" style="width:900px;">
<article class="module width_full" style="width:900px;">
<header><h3 style="text-align: center">Shto Artikull </h3></header>
<div id="Div1" class="module_content" runat="server">
<asp:Label ID="Label1" runat="server" style="font-weight: 700">Tema</asp:Label>
<fieldset>
<asp:TextBox ID="txtTema" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTema" runat="server"
ControlToValidate="txtTema" Display="Dynamic"
ErrorMessage="Kjo fushe eshte e nevojshme" style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset><br />
<asp:Label ID="Label6" runat="server" style="font-weight: 700">Abstrakti</asp:Label>
<fieldset>
<asp:TextBox ID="txtAbstrakti" style="height:250px;" Textmode="Multiline" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorAbstrakti" runat="server"
ControlToValidate="txtAbstrakti" ErrorMessage="Kjo fushe eshte e nevojshme"
style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset>
<asp:Label ID="lblData" runat="server" style="font-weight: 700">Data e Publikimit</asp:Label>
<fieldset>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox>
</fieldset>
<asp:Label ID="lblKeywords" runat="server" style="font-weight: 700">Keywords</asp:Label>
<fieldset>
<asp:TextBox ID="txtKeywords" runat="server"></asp:TextBox>
</fieldset>
<br />
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<div>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Insert"
/>
</div><br />
<strong>Ngarko Artikull</strong><br />
<asp:FileUpload ID="FileUploadArtikull" runat="server" /><br />
<br />
<asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />
</div>
</article>
</section>
</FooterTemplate>
</asp:DataList>
</asp:Content>
It shows this error:
Compiler Error Message: CS0103: The name 'e' does not exist in the
current context
In this line:
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
In your bind method you are calling an object e that doesn't exist. If the dropdownlist isn't inside a bound element, you can just reference the front code directly, e.g.
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
without finding the control as long as it is runat="server"
UPDATE
Okay, so you need to add an OnItemCreated event in your datalist
OnItemCreated="datalist2_OnItemCreated"
Then in that method you need this
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
That will work for if you only have the footer, if you add an itemtemplate then you just need to get rid of the check for the footer and on each item creation grab that dropdownlist for that item
I was trying to make a custom application form. I've added some control like TextBox and Button so far everything is fine until I modified some of the TextBox with a DropDownList control. When I click the add button it returns an error:
'categoryDropDownList' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
I've attached the sample code of my code behind:
public partial class Test2 : System.Web.UI.Page
{
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["LibrarySystemConnectionString"].ConnectionString;
}
private void execution(string bookid, string booktitle, string lastname, string firstname, string description, string categoryid, string dateadded, string quantity, string statusid)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO TblBooks(bookid, booktitle, lastname, firstname, description, categoryid, dateadded, quantity, statusid) VALUES "+" (#bookid, #booktitle,#lastname, #firstname, #description, #categoryid, #dateadded, #quantity, #statusid)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] pram = new SqlParameter[9];
pram[0] = new SqlParameter("#bookid", SqlDbType.BigInt, 64);
pram[1] = new SqlParameter("#booktitle", SqlDbType.NVarChar, 50);
pram[2] = new SqlParameter("#lastname", SqlDbType.NVarChar, 50);
pram[3] = new SqlParameter("#firstname", SqlDbType.NVarChar, 50);
pram[4] = new SqlParameter("#description", SqlDbType.NVarChar, 200);
pram[5] = new SqlParameter("#categoryid", SqlDbType.Int, 32);
pram[6] = new SqlParameter("#quantity", SqlDbType.Int, 32);
pram[7] = new SqlParameter("#statusid", SqlDbType.Int, 32);
pram[8] = new SqlParameter("#dateadded", SqlDbType.DateTime, 32);
pram[0].Value = bookid;
pram[1].Value = booktitle;
pram[2].Value = lastname;
pram[3].Value = firstname;
pram[4].Value = description;
pram[5].Value = categoryid;
pram[6].Value = quantity;
pram[7].Value = statusid;
pram[8].Value = dateadded;
for (int i = 0; i < pram.Length; i++)
{
cmd.Parameters.Add(pram[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex_msg)
{
string msg = "Error occured while inserting";
msg += ex_msg.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (bookidTextBox.Text == "")
{
Response.Write("Please complete the form");
}
else
{
execution(bookidTextBox.Text, booktitleTextBox.Text, lastnameTextBox.Text, firstnameTextBox.Text, descriptionTextBox.Text, categoryDropDownList.SelectedValue, dateaddedTextBox.Text, quantityTextBox.Text, statusDropDownList.SelectedValue);
//conform.Visible = true;
bookidTextBox.Text = "";
booktitleTextBox.Text = "";
lastnameTextBox.Text = "";
firstnameTextBox.Text = "";
descriptionTextBox.Text = "";
categoryDropDownList.SelectedValue = "";
dateaddedTextBox.Text = "";
statusDropDownList.SelectedValue = "";
quantityTextBox.Text = "";
}
}
}
}
Here's the sample code of the form:
<table class="style1">
<tr>
<td class="style2">
ISBN:
</td>
<td class="style3">
<asp:TextBox ID="bookidTextBox" runat="server" Text='<%# Bind("bookid") %>'>
</asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator" runat="server" ControlToValidate="bookidTextBox" ErrorMessage="* " ValidationGroup="addbooks">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style2">
Title:
</td>
<td class="style3">
<asp:TextBox ID="booktitleTextBox" runat="server" Text='<%# Bind("booktitle") %>'>
</asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="booktitleTextBox" ErrorMessage="* " ValidationGroup="addbooks">
</asp:RequiredFieldValidator>
</td>
</tr>
... (cut some code here)
<tr>
<td class="style2">
Category:
</td>
<td class="style3">
<asp:DropDownList ID="categoryDropDownList" runat="server"
DataSourceID="categoryDataSource" DataTextField="name"
DataValueField="categoryid" >
</asp:DropDownList>
<asp:SqlDataSource ID="categoryDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [categoryid], [name] FROM [TblCategory]">
</asp:SqlDataSource>
</td>
</tr>
...
<tr>
<td class="style2">
Status:</td>
<td class="style3">
<asp:DropDownList ID="statusDropDownList" runat="server"
DataSourceID="statusDataSource" DataTextField="statusname"
DataValueField="statusid" >
</asp:DropDownList>
<asp:SqlDataSource ID="statusDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [statusid], [statusname] FROM [BookStatus]">
</asp:SqlDataSource>
</td>
</tr>
</table>
</div>
<asp:Button ID="AddBtn" runat="server" Text="Add" OnClick="Button1_Click" Width="100px" />
<br />
<br />
<b>Book List</b>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="bookid" DataSourceID="bookDataSource">
<Columns>
<asp:BoundField DataField="bookid" HeaderText="bookid" ReadOnly="True"
SortExpression="bookid" />
<asp:BoundField DataField="booktitle" HeaderText="booktitle"
SortExpression="booktitle" />
<asp:BoundField DataField="lastname" HeaderText="lastname"
SortExpression="lastname" />
<asp:BoundField DataField="firstname" HeaderText="firstname"
SortExpression="firstname" />
<asp:BoundField DataField="categoryid" HeaderText="categoryid"
SortExpression="categoryid" />
<asp:BoundField DataField="description" HeaderText="description"
SortExpression="description" />
<asp:BoundField DataField="dateadded" HeaderText="dateadded"
SortExpression="dateadded" />
<asp:BoundField DataField="statusid" HeaderText="statusid"
SortExpression="statusid" />
<asp:BoundField DataField="quantity" HeaderText="quantity"
SortExpression="quantity" />
<asp:CheckBoxField DataField="isdeleted" HeaderText="isdeleted"
SortExpression="isdeleted" />
</Columns>
</asp:GridView>
It worked when I try to convert the DropDownList to textbox but how can I bind it with a DropDownList control??
Help would be much appreciated! Thanks in advance.
Your DropDown is bound to SqlDataSource. When you execute categoryDropDownList.SelectedValue = "", the DropDown is looking for empty value in the data source, but can't find such, so it fails.
If might want to run dropDownList.ClearSelection() if this is what you are trying to achieve.
Here is simplified code example that would demonstrate the issue
protected void Page_Load(object sender, EventArgs e)
{
var items = new[] { new { Id = 1, Name = "Test1" }, new { Id = 2, Name = "Test2" } };
dropDownList.DataSource = items;
dropDownList.DataValueField = "Id";
dropDownList.DataTextField = "Name";
dropDownList.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
dropDownList.SelectedValue = ""; // trhows exception
dropDownList.ClearSelection(); // works
}
Read up on this:
http://msdn.microsoft.com/en-us/library/system.web.ui.page.enableeventvalidation.aspx