SQL Server 2008 filestream read into web page - c#

I have a SQL Server table with filestream enabled. I am able to upload files here and update as well. How do I read these files into an .aspx web page? The files are .pdf files.
There are 2 files are associated with each row.
I am reading the row into a .aspx page and at the bottom I want the files to open up one below the other. This is for the user to print the row with the files.
I have checked out the code suggested by #dinglemeyer. I do want to conver my pdf to image. I am assuming there is a simple way:
<asp:GridView ID="gridview_f" runat="server" ShowHeaderWhenEmpty="false" PageSize="2" DataKeyNames="ID" DataSourceID="sql_files" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="selID" runat="server" Text='<%# Bind("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="selFname" runat="server" Text='<%# Bind("filename") %>' />
<br />
<asp:image ID="selFile" runat="server" ImageUrl='<%# "Handler.ashx?id="+Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
// code behind for ginfing the grid as the parentId is extracted from other form values.
private void gridView_Data(string id)
{
sql_files.SelectCommand = "SELECT ID, filename from myFILESTABLE where PARENTID=" + id;
}
// Handler.ascx
public void ProcessRequest(HttpContext context)
{
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader sdr = null;
conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["my_dbconn"].ConnectionString);
try
{
cmd = new SqlCommand("SELECT filecontent from myFILESTABLE WHERE ID=" + context.Request.QueryString["ID"], conn);
conn.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
context.Response.ContentType = "content/pdf";
context.Response.BinaryWrite((byte[])sdr["filecontent"]);
}
sdr.Close();
}
finally
{
conn.Close();
}

My apologies for the delayed reply.From the link:http://weblogs.asp.net/aghausman/saving-and-retrieving-file-using-filestream-sql-server-2008 Here is my working code:
<asp:GridView ID="mygrid1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" DataSourceID="sql_file" OnRowCommand="gridview_f_RowCommand" GridLines="None" >
<Columns>
<asp:TemplateField HeaderText="S.No">
<ItemTemplate>
<asp:Label ID="Label12" runat="server" Text='<%# Container.DataItemIndex + 1 %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attachments" >
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("ID") %>' Visible="false" />
<asp:LinkButton ID="lLabel12" runat="server" Text='<%# Bind("myFileName") %>' CommandName="GetFile" CommandArgument='<%#Eval("ID") + "|" + Eval("myFileName") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
" >
The code behind:
protected void gridview_f_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName=="GetFile")
{
string[] ca = e.CommandArgument.ToString().Split('|');
SqlConnection objSqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString);
objSqlCon.Open();
SqlTransaction objSqlTran = objSqlCon.BeginTransaction();
SqlCommand objSqlCmd = new SqlCommand("spGet_getMyFile", objSqlCon, objSqlTran);
objSqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter objSqlParam1 = new SqlParameter("#ID", SqlDbType.VarChar);
objSqlParam1.Value = ca[0]; // e.CommandArgument;
objSqlCmd.Parameters.Add(objSqlParam1);
string path = string.Empty;
using (SqlDataReader sdr = objSqlCmd.ExecuteReader())
{
while (sdr.Read())
{
path = sdr[0].ToString();
}
}
objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran);
byte[] objContext = (byte[])objSqlCmd.ExecuteScalar();
SqlFileStream objSqlFileStream = new SqlFileStream(path, objContext, FileAccess.Read);
byte[] buffer = new byte[(int)objSqlFileStream.Length];
objSqlFileStream.Read(buffer, 0, buffer.Length);
objSqlFileStream.Close();
objSqlTran.Commit();
Response.AddHeader("Content-disposition", "attachment; filename=" + ca[1]);
Response.ContentType = "application/pdf";
Response.BinaryWrite(buffer);
}
}
The Stored procedure SpGet_getMyfile is:
CREATE PROCEDURE [dbo].[spGet_getMyFile]
(
#id BIGINT
)
AS
SELECT filestreamColumn.PathName()
FROM dbo.TableThatHasTheFileStream
WHERE Id=#id

Related

Image is not displaying after adding items to the cart

Failed to load resource: the server responded with a status of 404 ()
System.Byte[]:1
This error is coming on inspecting it
protected void AllData()
{
if (Session["AddProduct"].ToString() == "true")
{
Session["AddProduct"] = "false";
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("ImageID");
dt.Columns.Add("ImageName");
dt.Columns.Add("ImageFile");
dt.Columns.Add("Price");
if (Request.QueryString["Id"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
string cont = #"";
SqlConnection sqlcon = new SqlConnection(cont);
SqlCommand cmd = new SqlCommand();
string query = "select * from tblclothes where ImageID=" + Request.QueryString["Id"];
cmd.CommandText = query;
cmd.Connection = sqlcon;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
dr["ImageID"] = ds.Tables[0].Rows[0]["ImageID"].ToString();
dr["ImageName"] = ds.Tables[0].Rows[0]["ImageName"].ToString();
dr["ImageFile"] = ds.Tables[0].Rows[0]["ImageFile"].ToString();
dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
dt.Rows.Add(dr);
gvproducts.DataSource = dt;
gvproducts.DataBind();
Session["buyitems"] = dt;
}
this is the code
protected static string ReturnEncodedBase64UTF8(object rawImg)
{
string img = "data:image/jpg;base64,{0}"; //change image type if need be
string toEncodeAsBytes = rawImg.ToString();
string returnValue = System.Convert.ToString(toEncodeAsBytes);
return String.Format(img, returnValue);
}
<asp:GridView ID="gvproducts" OnRowDataBound="gvproducts_RowDataBound" ShowFooter="true" HeaderStyle-BackColor="Blue"
HeaderStyle-ForeColor="White" OnRowDeleting="gvproducts_RowDeleting" runat="server" AutoGenerateColumns="false"
EmptyDataText="No Data Available" FooterStyle-Font-Bold="true" Width="400px">
<Columns>
<%--<asp:BoundField DataField="S.No" HeaderText="S.No" />--%>
<asp:BoundField DataField="ImageId" HeaderText="Image Id" />
<asp:BoundField DataField="ImageName" HeaderText="Image Name" />
<%--<asp:ImageField DataImageUrlField="ImageFile" HeaderText="Image"></asp:ImageField>--%>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<%--<img src='../Images/ <%# Eval("ImageFile") %>' id="img" runat="server" />--%>
<asp:Image ID="img" runat="server" ImageUrl='<%# "data:Image/png;base64," + Eval("ImageFile") %>' />
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="OriginalFormat" HeaderText="Format" />--%>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblprice" runat="server" Text='<%# Eval("Price") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotalPrice" runat="server" Text="Total Price"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
Regarding you case, you need to do the following:
When getting the DataRow, you need to cast it to Byte[] and convert it to a Base64 string like this:
dr["ImageFile"] = Convert.ToBase64String((Byte[])ds.Tables[0].Rows[0]["ImageFile"]);
Once you have the Base64 string, then you can apply it to your control like this:
<img src='data:image/jpg;base64, <%# Eval("ImageFile")%>' />

How do I get my stored procedure to work inside my Visual Studio project?

I am using Visual Studio 2017 (Windows 10) and I have made an ASP.NET empty web application in C#.
In SQL Server Express, I wrote a stored procedure for edit, update and delete for my grid view. Earlier I have added strings for the edit, update and delete operations.
But for security reasons I now want a stored procedure to administrate my data. The stored procedure works correctly when I execute it in SSMS and all I have done so far is implemented the stored procedure into my code. But when I execute the code none changes can be made what so ever.
So the questions is how I should modify my code from here in Visual Studio in C# for the stored procedure to work when I execute my project?
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestUsers.Default" %>
<link href="TestUsers.css" rel="stylesheet" type="text/css" />
<!DOCTYPE html>
<link rel="stylesheet" href="TestUsers.css">
<link rel="shortcut icon" type="image/x-icon" href="~/orbitone.ico" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ESDTESTERS</title>
<%-- <meta http-equiv="refresh" content="20">--%>
</head>
<body>
<form id="form1" runat="server">
<div class="divC">
<asp:GridView ID="gvTestUsers" runat="server" AutoGenerateColumns="False" ShowFooter="True" DataKeyNames="tbl_users_key" ShowHeaderWhenEmpty="True" OnRowCommand="gvTestUsers_RowCommand" OnRowEditing="gvTestUsers_RowEditing" OnRowCancelingEdit="gvTestUsers_RowCancelingEdit"
OnRowDeleting="gvTestUsers_RowDeleting" OnRowUpdating="gvTestUsers_RowUpdating" HorizontalAlign="Center"
BackColor="#CCCCCC" BorderColor="#000000" BorderStyle="Solid" BorderWidth="3px" CellPadding="5" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Width="1470px" CellSpacing="2" ForeColor="Black">
<%--Theme Properties--%>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" Font-Size="Large" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
<Columns>
<asp:TemplateField HeaderText="tbl_users_key">
<ItemTemplate>
<asp:Label Text='<%# Eval("tbl_users_key") %>' runat="server" />
</ItemTemplate>
<%-- <EditItemTemplate>
<asp:TextBox ID="txtID" Text='<%# Eval("ID") %>' runat="server" />
</EditItemTemplate>--%>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label Text='<%# Eval("Name") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" Text='<%# Eval("Name") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNamefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CostCenter">
<ItemTemplate>
<asp:Label Text='<%# Eval("CostCenter") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCostCenter" Text='<%# Eval("CostCenter") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCostCenterfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:Label Text='<%# Eval("Employee") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployee" Text='<%# Eval("Employee") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FootPlate">
<ItemTemplate>
<asp:Label Text='<%# Eval("FootPlate") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFootPlate" Text='<%# Eval("FootPlate") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFootPlatefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="WirstCord">
<ItemTemplate>
<asp:Label Text='<%# Eval("WirstCord") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtWirstCord" Text='<%# Eval("WirstCord") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtWirstCordfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Excluded">
<ItemTemplate>
<asp:Label Text='<%# Eval("Excluded") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExcluded" Text='<%# Eval("Excluded") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExcludedfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:Label Text='<%# Eval("Comment") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtComment" Text='<%# Eval("Comment") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCommentfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/edit.png" runat="server" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/delete.png" runat="server" CommandName="Delete" ToolTip="Delete" Width="20px" Height="20px" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/save.png" runat="server" CommandName="Update" ToolTip="Update" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ImageUrl="~/GridImages/add.png" runat="server" CommandName="AddNew" ToolTip="Add New" Width="20px" Height="20px" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<asp:Label ID="lblSuccessMessage" Text="" runat="server" ForeColor="Green" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
<br />
<asp:Label ID="lblErrorMessage" Text="" runat="server" ForeColor="Red" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
</div>
</div>
</form>
</body>
</html>
Default.aspx.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.SqlClient;
using System.Data;
using System.Configuration;
namespace TestUsers
{
public partial class Default : System.Web.UI.Page
{
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
//string connectionString = "Server=KNANTE800;Database=dataterm;Trusted_Connection=True";
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
PopulateGridView();
}
}
void PopulateGridView()
{
DataTable dtbl = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("Select * FROM TBL_USERS", sqlCon);
sqlDa.Fill(dtbl);
}
if (dtbl.Rows.Count > 0)
{
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
}
else
{
dtbl.Rows.Add(dtbl.NewRow());
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
gvTestUsers.Rows[0].Cells.Clear();
gvTestUsers.Rows[0].Cells.Add(new TableCell());
gvTestUsers.Rows[0].Cells[0].ColumnSpan = dtbl.Columns.Count;
gvTestUsers.Rows[0].Cells[0].Text = "No Data Found.";
gvTestUsers.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
protected void gvTestUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("AddNew"))
{
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
//string query = "INSERT INTO TBL_USERS (Name,CostCenter,Employee,FootPlate,WirstCord,Excluded,Comment) VALUES (#Name,#CostCenter,#Employee,#FootPlate,#WirstCord,#Excluded,#Comment)";
SqlCommand sqlCmd = new SqlCommand("spEditTBL_USERS", sqlCon);
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
// sqlCmd.Parameters.AddWithValue("#tbl_users_key", (gvTestUsers.FooterRow.FindControl("txtIDfooter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#Name", (gvTestUsers.FooterRow.FindControl("txtNamefooter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#CostCenter", (gvTestUsers.FooterRow.FindControl("txtCostCenterfooter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#Employee", (gvTestUsers.FooterRow.FindControl("txtEmployeefooter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#FootPlate", (gvTestUsers.FooterRow.FindControl("txtFootPlatefooter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#WirstCord", (gvTestUsers.FooterRow.FindControl("txtWirstCordfooter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#Excluded", (gvTestUsers.FooterRow.FindControl("txtExcludedfooter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#Comment", (gvTestUsers.FooterRow.FindControl("txtCommentfooter") as TextBox).Text.Trim());
sqlCmd.ExecuteNonQuery();
PopulateGridView();
lblSuccessMessage.Text = "New Changes Complete.";
lblErrorMessage.Text = "";
}
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvTestUsers.EditIndex = e.NewEditIndex;
PopulateGridView();
}
protected void gvTestUsers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvTestUsers.EditIndex = -1;
PopulateGridView();
}
protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
//string query = "DELETE FROM TBL_USERS WHERE tbl_users_key = #id";
SqlCommand sqlCmd = new SqlCommand("spEditTBL_USERS", sqlCon);
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#id", Convert.ToInt32(gvTestUsers.DataKeys[e.RowIndex].Value.ToString()));
sqlCmd.ExecuteNonQuery();
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
//string query = "UPDATE TBL_USERS SET Name=#Name,CostCenter=#CostCenter,Employee=#Employee,FootPlate=#FootPlate,WirstCord=#WirstCord,Excluded=#Excluded,Comment=#Comment WHERE tbl_users_key = #id";
SqlCommand sqlCmd = new SqlCommand("spEditTBL_USERS", sqlCon);
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
// sqlCmd.Parameters.AddWithValue("#tbl_users_key", (gvTestUsers.FooterRow.FindControl("txtIDfooter") as TextBox).Text.Trim());//
sqlCmd.Parameters.AddWithValue("#Name", (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#CostCenter", (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#Employee", (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#FootPlate", (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#WirstCord", (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#Excluded", (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#Comment", (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("#id", Convert.ToInt32(gvTestUsers.DataKeys[e.RowIndex].Value.ToString()));
sqlCmd.ExecuteNonQuery();
gvTestUsers.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
}
}
Stored procedure:
-- =============================================
-- Author: Måns Bodin
-- Create date: 2021-09.-23
-- Description: used for update ESD users
-- =============================================
ALTER PROCEDURE [dbo].[spEditTBL_USERS]
#ID int = null,
#NAME varchar(255),
#COSTCENTER varchar(10),
#EMPLOYEE varchar(32),
#FOOTPLATE bit,
#WIRSTCORD bit,
#EXCLUDED bit,
#MODE smallint,
#COMMENT varchar(255),
#MSG varchar(255) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #CHECK AS int
SET #MSG = ''
IF #MODE = 0
BEGIN
SELECT #CHECK = COUNT(1)
FROM TBL_USERS
WHERE employee = #EMPLOYEE
IF #CHECK != 0
BEGIN
SET #MSG = 'Employee already exists in database.'
RETURN 99
END
INSERT INTO TBL_USERS (Name, CostCenter, Employee, FootPlate, WIRSTCORD, Excluded, Comment)
VALUES (#NAME, #COSTCENTER, #EMPLOYEE, #FOOTPLATE, #WIRSTCORD, #EXCLUDED, #COMMENT)
RETURN 0
END
IF #MODE = 1
BEGIN
UPDATE TBL_USERS
SET Name = #NAME,
CostCenter = #COSTCENTER,
Employee = #EMPLOYEE,
FootPlate = #FOOTPLATE,
WIRSTCORD = #WIRSTCORD,
Excluded = #EXCLUDED,
Comment = #COMMENT
WHERE tbl_users_key = #ID
RETURN 9
END
IF #MODE = 2
BEGIN
DELETE FROM TBL_USERS
WHERE tbl_users_key = #ID
RETURN 0
END
-- select * from TBL_USERS
END
I modified it like this and it worked very nicely for me!
RowUpdating:
{
try
{
//Parameters Set From Grid
string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string tmpsMsg = "";
//Call function for SP_UPDATE
bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, Convert.ToBoolean(tmpFootPlate), Convert.ToBoolean(tmpWirstCord), Convert.ToBoolean(tmpExcluded), tmpComment,ref tmpsMsg,1);
//Reload Page
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
RowDeleting:
{
try
{
{
gvTestUsers.EditIndex = e.RowIndex;
PopulateGridView();
//Parameters for delete operation
string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string dltsMsg = "";
//Call function for SP_Delete
bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, Convert.ToBoolean(dltFootPlate), Convert.ToBoolean(dltWirstCord), Convert.ToBoolean(dltExcluded), dltComment,ref dltsMsg,2);
if (FuncDelete == false)
{
lblErrorMessage.Text = dltsMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
gvTestUsers.EditIndex = -1;
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
RowCommand:
{
try
{
if (e.CommandName.Equals("AddNew"))
{
int tbl_users_key = 0;
TextBox myTxt;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtNamefooter"));
string Name;
Name = myTxt.Text;
string CostCenter;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCostCenterfooter"));
CostCenter = myTxt.Text;
string Employee;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtEmployeefooter"));
Employee = myTxt.Text;
Boolean FootPlate;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtFootPlatefooter"));
// string tmpFootPlate = (gvTestUsers.FooterRow.FindControl("txtFootPlate") as TextBox).Text.Trim();
// boo Convert.ToBoolean(tmpFootPlate)
FootPlate = Convert.ToBoolean(myTxt.Text);
Boolean WirstCord;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtWirstCordfooter"));
WirstCord = Convert.ToBoolean(myTxt.Text);
Boolean Excluded;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtExcludedfooter"));
Excluded = Convert.ToBoolean(myTxt.Text);
string Comment;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCommentfooter"));
Comment = myTxt.Text;
string sMsg;
sMsg = "";
bool btest = fcEditTBL_USERS(tbl_users_key, Name, CostCenter, Employee, FootPlate, WirstCord, Excluded, Comment, ref sMsg,0);
if (btest == false)
{
lblErrorMessage.Text = sMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = Name + " Was Added To Record.";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}

insert date in wrong way

im trying to insert into table date in this type dd/mm/yyyy.
in the mysql i set the data type to DATE.
when i click add and insert the date this error is shown.
"mysql.data.types.mysqlconversionexpection {"Unable to convert MySQL date/time value to System.DateTime"}"
i cant find the mistake.
thanks alot!!
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 MySql.Data.MySqlClient;
namespace WebApplication1
{
public partial class usageDisp : System.Web.UI.Page
{
string connectionstring = #"Data Source=localhost; Database=globaldotdb; user ID=root; Password=peleg1708";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//check
BindData();
}
}
private void BindData()
{
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
MySqlDataAdapter adp = new MySqlDataAdapter(("SELECT tblusage.codeUsage,tblcustom.Customer, tblvendor.Vendor, tblusage.dateStart, tblusage.dateEnd, tblregion.Region, tblservice.Service, tblservice.unit, tblusage.isSecure,tblusage.Usages FROM ((((tblvendor INNER JOIN tblusage ON tblvendor.codeVendor = tblusage.codeVendor) INNER JOIN tblservice ON tblusage.codeService = tblservice.codeService) INNER JOIN tblregion ON tblusage.codeRegion = tblregion.codeRegion) INNER JOIN tblcustom ON tblusage.codeCust = tblcustom.codeCust)"), cn);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
gv.DataSource = dt;
gv.DataBind();
}
}
}
protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int codeusage = int.Parse(gv.DataKeys[e.RowIndex].Value.ToString());
deleteusage(codeusage);
BindData();
}
private void deleteusage(int codeusage)
{
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
string query = "DELETE FROM tblusage WHERE codeUsage=" + codeusage + " ";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
}
}
protected void gv_DataBound(object sender, EventArgs e)
{
DropDownList DDLCu = gv.FooterRow.FindControl("DDLCu") as DropDownList;
DropDownList DDLVe = gv.FooterRow.FindControl("DDLVe") as DropDownList;
DropDownList DDLSe = gv.FooterRow.FindControl("DDLSe") as DropDownList;
DropDownList DDLRe = gv.FooterRow.FindControl("DDLRe") as DropDownList;
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
MySqlDataAdapter Cadp = new MySqlDataAdapter(("SELECT * from tblcustom"), cn);
DataTable Cdt = new DataTable();
Cadp.Fill(Cdt);
if (Cdt.Rows.Count > 0)
{
DDLCu.DataSource = Cdt;
DDLCu.DataTextField = "Customer";
DDLCu.DataValueField = "codeCust";
DDLCu.DataBind();
}
MySqlDataAdapter Vadp = new MySqlDataAdapter(("SELECT * from tblvendor"), cn);
DataTable Vdt = new DataTable();
Vadp.Fill(Vdt);
if (Vdt.Rows.Count > 0)
{
DDLVe.DataSource = Vdt;
DDLVe.DataTextField = "Vendor";
DDLVe.DataValueField = "codeVendor";
DDLVe.DataBind();
}
MySqlDataAdapter Sadp = new MySqlDataAdapter(("SELECT * from tblservice"), cn);
DataTable Sdt = new DataTable();
Sadp.Fill(Sdt);
if (Sdt.Rows.Count > 0)
{
DDLSe.DataSource = Sdt;
DDLSe.DataTextField = "Service";
DDLSe.DataValueField = "codeService";
DDLSe.DataBind();
}
MySqlDataAdapter Radp = new MySqlDataAdapter(("SELECT * from tblregion"), cn);
DataTable Rdt = new DataTable();
Radp.Fill(Rdt);
if (Rdt.Rows.Count > 0)
{
DDLRe.DataSource = Rdt;
DDLRe.DataTextField = "Region";
DDLRe.DataValueField = "codeRegion";
DDLRe.DataBind();
}
}
}
protected void lnkAdd_Click(object sender, EventArgs e)
{
DropDownList DDLCu = gv.FooterRow.FindControl("DDLCu") as DropDownList;
DropDownList DDLVe = gv.FooterRow.FindControl("DDLVe") as DropDownList;
DropDownList DDLSe = gv.FooterRow.FindControl("DDLSe") as DropDownList;
DropDownList DDLRe = gv.FooterRow.FindControl("DDLRe") as DropDownList;
DropDownList DDLIS = gv.FooterRow.FindControl("DDLIS") as DropDownList;
TextBox txtds = (TextBox)gv.FooterRow.FindControl("TBDS");
TextBox txtde = (TextBox)gv.FooterRow.FindControl("TBDE");
TextBox txtus = (TextBox)gv.FooterRow.FindControl("TextBoxUnit");
int usage = int.Parse(txtus.Text);
int cc = int.Parse(DDLCu.SelectedValue);
int cv = int.Parse(DDLVe.SelectedValue);
int cs = int.Parse(DDLSe.SelectedValue);
int cr = int.Parse(DDLRe.SelectedValue);
int iss = int.Parse(DDLIS.SelectedValue);
string DS = txtds.Text;
string DE = txtde.Text;
add(cc, cv, cs, cr, usage, iss, DE, DS);
BindData();
Response.Redirect("http://localhost:56717/usageDisp.aspx");
}
private void add(int cc, int cv, int cs, int cr,int usag,int isecure, string ds, string de)
{
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
string query = "insert into tblusage(codeCust,codeVendor,codeService,codeRegion,Usages,isSecure,dateStart,dateEnd) values (" + cc + "," + cv + "," + cs + "," + cr + "," + usag + "," + isecure + "," + ds + "," + de + ") ";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
}
}
protected void CalendarStart_SelectionChanged(object sender, EventArgs e)
{
TextBox txtds = (TextBox)gv.FooterRow.FindControl("TBDS");
Calendar cas = gv.FooterRow.FindControl("CalendarStart") as Calendar;
txtds.Text = cas.SelectedDate.ToString("d");
}
protected void CalendarEnd_SelectionChanged(object sender, EventArgs e)
{
TextBox txtde = (TextBox)gv.FooterRow.FindControl("TBDE");
Calendar cas = gv.FooterRow.FindControl("CalendarEnd") as Calendar;
txtde.Text = cas.SelectedDate.ToString("d");
}
}
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="usageDisp.aspx.cs" Inherits="WebApplication1.usageDisp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="usageDisp" runat="server">
<asp:GridView ID="gv" runat="server"
DataKeyNames="codeUsage"
onrowdeleting="gv_RowDeleting"
AutoGenerateColumns="False" ondatabound="gv_DataBound" ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="codeusage" Visible="False">
<EditItemTemplate>
<asp:TextBox ID="txtcode" runat="server" Text='<%# Eval("codeUsage") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("codeUsage") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer">
<EditItemTemplate>
<asp:TextBox ID="TXTCust" runat="server" Text='<%# Eval("Customer") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDLCu" runat="server" AutoPostBack="True">
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Customer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Vendor">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Vendor") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDLVe" runat="server" AutoPostBack="True">
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Vendor") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dateStart">
<EditItemTemplate>
<asp:TextBox ID="TXTDS" runat="server" Text='<%# Eval("dateStart") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Calendar ID="CalendarStart" runat="server" BackColor="#FFFFCC"
BorderColor="#FFCC66" BorderWidth="1px" DayNameFormat="Shortest"
Font-Names="Verdana" Font-Size="8pt" ForeColor="#663399" Height="108px"
ShowGridLines="True" Width="132px"
onselectionchanged="CalendarStart_SelectionChanged">
<DayHeaderStyle BackColor="#FFCC66" Font-Bold="True" Height="1px" />
<NextPrevStyle Font-Size="9pt" ForeColor="#FFFFCC" />
<OtherMonthDayStyle ForeColor="#CC9966" />
<SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" />
<SelectorStyle BackColor="#FFCC66" />
<TitleStyle BackColor="#990000" Font-Bold="True" Font-Size="9pt"
ForeColor="#FFFFCC" />
<TodayDayStyle BackColor="#FFCC66" ForeColor="White" />
</asp:Calendar>
<asp:TextBox ID="TBDS" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("dateStart") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dateEnd">
<EditItemTemplate>
<asp:TextBox ID="TXTDE" runat="server" Text='<%# Eval("dateEnd") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Calendar ID="CalendarEnd" runat="server" BackColor="White"
BorderColor="#3366CC" BorderWidth="1px" CellPadding="1"
DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt"
ForeColor="#003399" Height="108px" Width="132px"
onselectionchanged="CalendarEnd_SelectionChanged">
<DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" />
<NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" />
<OtherMonthDayStyle ForeColor="#999999" />
<SelectedDayStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SelectorStyle BackColor="#99CCCC" ForeColor="#336666" />
<TitleStyle BackColor="#003399" BorderColor="#3366CC" BorderWidth="1px"
Font-Bold="True" Font-Size="10pt" ForeColor="#CCCCFF" Height="25px" />
<TodayDayStyle BackColor="#99CCCC" ForeColor="White" />
<WeekendDayStyle BackColor="#CCCCFF" />
</asp:Calendar>
<asp:TextBox ID="TBDE" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("dateEnd") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="service">
<EditItemTemplate>
<asp:TextBox ID="TXTSe" runat="server" Text='<%# Eval("Service") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDLSe" runat="server" AutoPostBack="True">
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Eval("Service") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="region">
<EditItemTemplate>
<asp:TextBox ID="TXTRe" runat="server" Text='<%# Eval("Region") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDLRe" runat="server" AutoPostBack="True">
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# Eval("Region") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="isSecure">
<EditItemTemplate>
<asp:TextBox ID="TXTIS" runat="server" Text='<%# Eval("isSecure") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDLIS" runat="server">
<asp:ListItem Value="1">true</asp:ListItem>
<asp:ListItem Value="0">false</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label8" runat="server" Text='<%# Eval("isSecure") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="unit">
<EditItemTemplate>
<asp:TextBox ID="TXTunit" runat="server" Text='<%# Eval("unit") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval("unit") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="usage">
<EditItemTemplate>
<asp:TextBox ID="TXTusage" runat="server" Text='<%# Eval("Usages") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBoxUnit" runat="server"></asp:TextBox>
<asp:LinkButton ID="lnkAdd" runat="server" onclick="lnkAdd_Click">add</asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label10" runat="server" Text='<%# Eval("Usages") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Operation" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<div>
</div>
</form>
</body>
</html>
you just need to add Convert.ToDateTime() , then your query'll definately work.
but, your doing it in a wrong way.
use Parameterized Query,
A parameterized query is a query in which placeholders are used for
parameters and the parameter values are supplied at execution time.
The most important reason to use parameterized queries is to avoid SQL
injection attacks
In your case, you need to change the insert query:
string query = "insert into tblusage(codeCust,codeVendor,codeService,codeRegion,Usages,isSecure,dateStart,dateEnd) values (" + cc + "," + cv + "," + cs + "," + cr + "," + usag + "," + isecure + "," + Convert.ToDateTime(ds) + "," + Convert.ToDateTime(de) + ") ";
Or, You can change the ds and dt variable datatype
CultureInfo provider = CultureInfo.InvariantCulture;
string format="dd/mm/yyyy";//define your datetime format here
DateTime ds=DateTime.ParseExact(textbox1.Text, format, provider);
DateTime de=DateTime.ParseExact(textbox2.Text, format, provider);
and then pass it to the query,like
string query = "insert into tblusage(codeCust,codeVendor,codeService,codeRegion,Usages,isSecure,dateStart,dateEnd) values (" + cc + "," + cv + "," + cs + "," + cr + "," + usag + "," + isecure + "," +ds + "," + de + ") ";
Edit 2:
private void add(int cc, int cv, int cs, int cr,int usag,int isecure, string ds, string de)
{
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
string query = "insert into tblusage(codeCust,codeVendor,codeService,codeRegion,Usages,isSecure,dateStart,dateEnd) values (#cc,#cv,#cs,#cr,#usag,#isecure,#ds,#de) ";
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd .Parameters.Add("#cc",MySqlDbType.Int).Value=cc;
cmd .Parameters.Add("#cv",MySqlDbType.Int).Value=cv;
cmd .Parameters.Add("#cs",MySqlDbType.Int).Value=cs;
cmd .Parameters.Add("#cr",MySqlDbType.Int).Value=cr;
cmd .Parameters.Add("#usag",MySqlDbType.Int).Value=usag;
cmd .Parameters.Add("#isecure",MySqlDbType.Int).Value=isecure;
cmd .Parameters.Add("#ds",MySqlDbType.Date).Value=ds;
cmd .Parameters.Add("#de",MySqlDbType.Date).Value=de;
cn.Open();
cmd.ExecuteNonQuery();
}
}
Please consider using parametric queries & Convert.toDateTime().
private void add(int cc, int cv, int cs, int cr,int usag,int isecure, string ds, string de)
{
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
using (var sqlcmd = new SqlCommand())
{
sqlcmd.Connection = cn;
sqlcmd.CommandText = "insert into tblusage(codeCust,codeVendor,codeService,codeRegion,Usages,isSecure,dateStart,dateEnd) values (#codeCust,
#codeVendor, #codeService, #codeRegion, #Usages, #isSecure, #dateStart, #dateEnd)")
sqlcmd.Parameters.AddWithValue("#codeCust", cc);
sqlcmd.Parameters.AddWithValue("#codeVendor", cv);
sqlcmd.Parameters.AddWithValue("#codeService", cs);
sqlcmd.Parameters.AddWithValue("#codeRegion", cr);
sqlcmd.Parameters.AddWithValue("#Usages", usag);
sqlcmd.Parameters.AddWithValue("#isSecure", isecure);
sqlcmd.Parameters.AddWithValue("#dateStart", Convert.ToDateTime(ds));
sqlcmd.Parameters.AddWithValue("#dateEnd", Convert.ToDateTime(de));
cn.open();
sqlcmd.ExecuteNonQuery();
}
}
}
You have to specify date format.
Sample code:
str_to_date(de,"%d/%m/%Y")
str_to_date is mysql function. Kindly refer MySQL documentation.
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Verify at http://sqlfiddle.com/#!9/46d5b/1

System.FormatException and delete not working

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.

Datagrid with DropDownList columns in edit mode

I have an editable DataGrid with an EditCommandColumn. Initially the DataGrid is showing the correct values pulled from the database. The problem is that when a row goes into edit mode the columns with DropDownLists show the first value in the list and not the correct value. What would cause this and how do I fix it?
here is the .aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Kunde_drop.aspx.cs"Inherits ="Kunde_drop._Default" %>
<html>
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<table id="Table1" style="height:176;width:344" cellspacing="1" cellpadding="1" border="0">
......
......
......
<asp:DataGrid id="DataGrid1" Runat="server" DataKeyField="kundennr"
AutoGenerateColumns="False" EditItemStyle-BackColor="#F7F7F7"
HeaderStyle-BackColor="#F7F7F7" CellPadding="4" HorizontalAlign="Left">
<FooterStyle BackColor="PaleGoldenrod"></FooterStyle>
<SelectedItemStyle BackColor="Control"></SelectedItemStyle>
<EditItemStyle BackColor="#F7F7F7"></EditItemStyle>
<ItemStyle BackColor="White"></ItemStyle>
<HeaderStyle BackColor="DarkKhaki"></HeaderStyle>
<Columns>
<asp:TemplateColumn HeaderText="Kundennr">
<HeaderStyle Width="30px"></HeaderStyle>
<ItemTemplate>
<asp:Literal ID="Label" Text='<%# DataBinder.Eval(Container.DataItem, "kundennr")%>' Runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Kundetyp">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<asp:Label ID="lblKtyp" Text='<%# DataBinder.Eval(Container.DataItem, "kundentyp")%>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:dropdownlist ID="Dropdownlist1" DataSource='<%# LoadKundentype() %>'
DataTextField="kundertype" runat="server"></asp:dropdownlist>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Firma">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "firma") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Textbox2" Text='<%# DataBinder.Eval(Container.DataItem, "firma") %>'Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Anrede">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "anrede") %>
</ItemTemplate>
<EditItemTemplate>
<asp:dropdownlist ID="Dropdownlist2" DataSource='<%# LoadAnrede() %>'
DataTextField="anrede" runat="server"></asp:dropdownlist>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Name">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "name1") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Textbox16" Text='<%# DataBinder.Eval(Container.DataItem, "name1") %>'Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Ansprechperson">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "ansprechperson") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Textbox17" Text='<%# ataBinder.Eval(Container.DataItem,"ansprechperson") %>' Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Strasse">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "strasse") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Textbox18" Text='<%# DataBinder.Eval(Container.DataItem, "strasse") %>' Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Ort">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "ort") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Textbox19" Text='<%# DataBinder.Eval(Container.DataItem, "ort") %>' Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="PLZ">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "plz") %>
</ItemTemplate>
<EditItemTemplate>
<asp:Textbox ID="Textbox20" Text='<%# DataBinder.Eval(Container.DataItem, "plz") %>' Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Email">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "email") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Textbox21" Text='<%# DataBinder.Eval(Container.DataItem, "email") %>' Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Telefon 1">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "telefon1") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Textbox22" Text='<%# DataBinder.Eval(Container.DataItem, "telefon1") %>' Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Telefon 2" ItemStyle-Wrap="False">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "telefon2") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Textbox23" Text='<%# DataBinder.Eval(Container.DataItem, "telefon2") %>' Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Region">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "region") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Textbox24" Text='<%# DataBinder.Eval(Container.DataItem, "region") %>' Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel" EditText="Edit"></asp:EditCommandColumn>
<asp:ButtonColumn Text="Delete" CommandName="Delete"></asp:ButtonColumn>
</Columns>
</asp:DataGrid></td>
</tr>
</table>
</form>
</body>
</html>
There is the .aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web.SessionState;
using System.Web.UI.HtmlControls;
using MySql.Data;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
namespace Kunde_drop
{
public partial class _Default : System.Web.UI.Page
{
private const string ConnStr = "SERVER=serv;DATABASE=dbk;UID=user;PASSWORD=pas;";
string strSort;
string strerrorMsg;
string strscriptString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (strSort == "")
{
strSort = "IntegerValue";
}
BindDataGrid();
}
}
public ICollection LoadKundentype()
{
MySqlConnection con1 = new MySqlConnection(ConnStr);
con1.Open();
string cmd1 = "SELECT * FROM kunderetyp WHERE 1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd1, con1);
DataSet ds = new DataSet();
da.Fill(ds, "kundertype");
DataTable dt = ds.Tables["kundertype"];
return dt.DefaultView;
}
public ICollection LoadAnrede()
{
MySqlConnection con2 = new MySqlConnection(ConnStr);
con2.Open();
string cmd2 = "SELECT * FROM anrede WHERE 1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd2, con2);
DataSet ds = new DataSet();
da.Fill(ds, "anrede");
DataTable dt = ds.Tables["anrede"];
return dt.DefaultView;
}
private void BindDataGrid()
{
using (MySqlConnection con = new MySqlConnection(ConnStr))
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM kunde", con))
{
con.Open();
DataGrid1.DataSource = cmd.ExecuteReader(
CommandBehavior.CloseConnection |
CommandBehavior.SingleResult);
DataGrid1.DataBind();
}
}
private void UpdateInfo(int kundennr, string kundentyp, string firma, string anrede, string name1, string ansprechperson, string strasse, string ort, int plz, string email, string telefon1, string telefon2, string region)
{
using (MySqlConnection con = new MySqlConnection(ConnStr))
using (MySqlCommand cmd = new MySqlCommand("UPDATE kunde SET kundentyp = #kundentyp, firma = #firma, anrede = #anrede, name1 = #name1, ansprechperson = #ansprechperson, strasse = #strasse, ort = #ort, plz = #plz, email = #email, telefon1 = #telefon1, telefon2 = #telefon2, region = #region WHERE kundennr = #kundennr", con))
{
cmd.Parameters.Add("#kundentyp", MySqlDbType.VarChar, 255).Value = kundentyp;
cmd.Parameters.Add("#firma", MySqlDbType.VarChar, 255).Value = firma;
cmd.Parameters.Add("#anrede", MySqlDbType.VarChar, 255).Value = anrede;
cmd.Parameters.Add("#name1", MySqlDbType.VarChar, 255).Value = name1;
cmd.Parameters.Add("#ansprechperson", MySqlDbType.VarChar, 255).Value = ansprechperson;
cmd.Parameters.Add("#strasse", MySqlDbType.VarChar, 255).Value = strasse;
cmd.Parameters.Add("#ort", MySqlDbType.VarChar, 255).Value = ort;
cmd.Parameters.Add("#plz", MySqlDbType.Int32).Value = plz;
cmd.Parameters.Add("#email", MySqlDbType.VarChar, 255).Value = email;
cmd.Parameters.Add("#telefon1", MySqlDbType.VarChar, 20).Value = telefon1;
cmd.Parameters.Add("#telefon2", MySqlDbType.VarChar, 45).Value = telefon2;
cmd.Parameters.Add("#region", MySqlDbType.VarChar, 255).Value = region;
cmd.Parameters.Add("#kundennr", MySqlDbType.Int64).Value = kundennr;
con.Open();
cmd.ExecuteNonQuery();
}
}
private void DeleteInfo(int kundennr)
{
using (MySqlConnection con = new MySqlConnection(ConnStr))
using (MySqlCommand cmd = new MySqlCommand("DELETE FROM kunde WHERE kundennr = #kundennr", con))
{
cmd.Parameters.Add("#kundennr", MySqlDbType.Int64).Value = kundennr;
con.Open();
cmd.ExecuteNonQuery();
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_CancelCommand);
this.DataGrid1.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_EditCommand);
this.DataGrid1.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.DataGrid1_SortCommand);
this.DataGrid1.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_UpdateCommand);
this.DataGrid1.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_DeleteCommand);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void DataGrid1_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
}
private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
BindDataGrid();
}
protected void DataGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
DataGrid1.EditItemIndex = e.NewEditIndex;
BindDataGrid();
}
private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
try
{
int cUsrID;
string strKundentyp;
string strFirma;
string strAnrede;
string strName1;
string strAnsprechperson;
string strStrasse;
string strOrt;
string strEmail;
string strPlz;
int intPlz;
string strTelefon1;
string strTelefon2;
string strRegion;
Literal ltID;
TextBox txtTempFirma;
DropDownList drdTempAnrede;
TextBox txtTempName1;
TextBox txtTempAnsprechperson;
TextBox txtTempStrasse;
TextBox txtTempOrt;
TextBox txtTempPlz;
TextBox txtTempEmail;
TextBox txtTempTelefon1;
TextBox txtTempTelefon2;
TextBox txtTempRegion;
DropDownList drdList;
drdList = (System.Web.UI.WebControls.DropDownList)e.Item.Cells[1].FindControl("Dropdownlist1");
strKundentyp = drdList.Text;
ltID = (System.Web.UI.WebControls.Literal)e.Item.Cells[0].FindControl("Label");
cUsrID = Convert.ToInt32(ltID.Text);
txtTempFirma = (System.Web.UI.WebControls.TextBox)e.Item.Cells[2].FindControl("Textbox2");
strFirma = txtTempFirma.Text;
drdTempAnrede = (System.Web.UI.WebControls.DropDownList)e.Item.Cells[3].FindControl("Dropdownlist2");
strAnrede = drdTempAnrede.Text;
txtTempName1 = (System.Web.UI.WebControls.TextBox)e.Item.Cells[4].FindControl("Textbox16");
strName1 = txtTempName1.Text;
txtTempAnsprechperson = (System.Web.UI.WebControls.TextBox)e.Item.Cells[5].FindControl("Textbox17");
strAnsprechperson = txtTempAnsprechperson.Text;
txtTempStrasse = System.Web.UI.WebControls.TextBox)e.Item.Cells[6].FindControl("Textbox18");
strStrasse = txtTempStrasse.Text;
txtTempOrt = (System.Web.UI.WebControls.TextBox)e.Item.Cells[7].FindControl("Textbox19");
strOrt = txtTempOrt.Text;
txtTempPlz = (System.Web.UI.WebControls.TextBox)e.Item.Cells[8].FindControl("TextBox20");
strPlz = txtTempPlz.Text;
intPlz = Convert.ToInt32(strPlz);
txtTempEmail = (System.Web.UI.WebControls.TextBox)e.Item.Cells[9].FindControl("Textbox21");
strEmail = txtTempEmail.Text;
txtTempTelefon1 = (System.Web.UI.WebControls.TextBox)e.Item.Cells[10].FindControl("Textbox22");
strTelefon1 = txtTempTelefon1.Text;
txtTempTelefon2 = (System.Web.UI.WebControls.TextBox)e.Item.Cells[11].FindControl("Textbox23");
strTelefon2 = txtTempTelefon2.Text;
txtTempRegion = (System.Web.UI.WebControls.TextBox)e.Item.Cells[12].FindControl("Textbox24");
strRegion = txtTempRegion.Text;
UpdateInfo(cUsrID, strKundentyp, strFirma, strAnrede, strName1, strAnsprechperson, strStrasse, strOrt, intPlz, strEmail, strTelefon1, strTelefon2, strRegion);
DataGrid1.EditItemIndex = -1;
BindDataGrid();
}
catch (Exception ex)
{
strerrorMsg = ex.Message.Replace("'", #"""");
strscriptString = "<script language = Javascript>";
strscriptString += "window.status = '" + strerrorMsg + "';";
strscriptString += "</script>";
RegisterStartupScript("clientScript", strscriptString);
}
}
private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
try
{
int cID;
Literal ltID = null;
string ss = string.Empty;
ltID = (System.Web.UI.WebControls.Literal)e.Item.Cells[0].FindControl("Label");
cID = Convert.ToInt32(ltID.Text);
DeleteInfo(cID);
BindDataGrid();
}
catch (Exception ex)
{
strerrorMsg = ex.Message.Replace("'", #"""");
strscriptString = "<script language = Javascript>";
strscriptString += "window.status = '" + strerrorMsg + "';";
strscriptString += "</script>";
RegisterStartupScript("clientScript", strscriptString);
}
}
private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = -1;
BindDataGrid();
}
}
}
First, add DataValueField to your DropDownLists:
<asp:dropdownlist
ID="Dropdownlist1"
DataValueField="kundertype"
...
<asp:dropdownlist
ID="Dropdownlist2"
DataValueField="anrede"
...
Second, add an onitemdatabound event to your DataGrid:
<asp:DataGrid
onitemdatabound="DataGrid1_ItemDataBound"
...
Third, add this method to handle the ItemDataBound event:
protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.EditItem)
{
DropDownList dropDownList1 = (DropDownList)e.Item.FindControl("Dropdownlist1");
DataRowView dataItem1 = (DataRowView)e.Item.DataItem;
dropDownList1.SelectedValue = (string)dataItem1.Row["kundertype"];
DropDownList dropDownList2 = (DropDownList)e.Item.FindControl("Dropdownlist2");
DataRowView dataItem2 = (DataRowView)e.Item.DataItem;
dropDownList2.SelectedValue = (string)dataItem2.Row["anrede"];
}
}
Also note that the DataGrid control has been succeeded by the GridView. It might not be worth it for you to change, but you can check out the comparison here.

Categories

Resources