insert/update in GridView - c#

I'm using asp.net with C# and SQL server 2008 r2. I have Gridview to insert, update, and delete some data of employees.
I have two problems:
With the insert I got this error
System.NullReferenceException: Object reference not set to an instance of an object.
When I click on edit nothing happen. I thing it because of index in e.CommandName == "EditRow" but I'm not sure. I believe I'm going to get the same problem when else if e.CommandName == "UpdateRow"
Delete is working fine.
code in . aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="HR_System_v1.WebForm3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<p>
Enter Employee #<asp:TextBox ID="txtEmpNo" runat="server"
ontextchanged="txtEmpNo_TextChanged"></asp:TextBox>
</p>
<p>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="EmpNo,Qid"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2" ShowFooter="True" AutoGenerateColumns="False" CssClass="grid"
OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField >
<EditItemTemplate>
<asp:LinkButton ID="lbUpdate" runat="server" CommandArgument='<%# Eval("Qid") %>' CommandName="UpdateRow">Update</asp:LinkButton>
<asp:LinkButton ID="lbCancel" runat="server" CommandArgument='<%# Eval("EmpNo") %>' CommandName="CancelUpdate">Cancel</asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="lbEdit" runat="server" CommandArgument='<%# Eval("Qid") %>' CommandName="EditRow">Edit</asp:LinkButton>
<asp:LinkButton ID="lbdelete" runat="server" CommandArgument='<%# Eval("Qid") %>' CommandName="DeleteRow">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmpNo" SortExpression="EmpNo">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("EmpNo") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("EmpNo") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID= "lbInsert" runat="server" CommandName="Insert" ValidationGroup="INSERT">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QName" SortExpression="QName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("QName") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEditQName" ValidationGroup="Update" runat="server"
ControlToValidate="TextBox1" ErrorMessage="Please Enter QName"
ForeColor="Red">*</asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("QName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtQName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvInsertQName" runat="server"
ControlToValidate="txtQName" ValidationGroup="INSERT" ErrorMessage="Please Enter QName"
ForeColor="Red">*</asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QIssPlace" SortExpression="QIssPlace">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("QIssPlace") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEditQIssP" ValidationGroup="Update" runat="server"
ControlToValidate="TextBox2" ErrorMessage="Please Enter QIssPlace"
ForeColor="Red">*</asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("QIssPlace") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtQIssP" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvInsertQIssP" runat="server"
ControlToValidate="txtQIssP" ValidationGroup="INSERT" ErrorMessage="Please Enter QIssPlace"
ForeColor="Red">*</asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Field" SortExpression="Field">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Field") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEditeField" ValidationGroup="Update" runat="server"
ControlToValidate="TextBox3" ErrorMessage="Please Enter Field"
ForeColor="Red">*</asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Field") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtField" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvInsertField" runat="server"
ControlToValidate="txtField" ValidationGroup="INSERT" ErrorMessage="Please Enter Field"
ForeColor="Red">*</asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GradDate" SortExpression="GradDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("GradDate") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEditeGradD" ValidationGroup="Update" runat="server"
ControlToValidate="TextBox4" ErrorMessage="Please Enter GradDate"
ForeColor="Red">*</asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("GradDate") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtGradD" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvInsertGradD" runat="server"
ControlToValidate="txtGradD" ValidationGroup="INSERT" ErrorMessage="Please Enter GradDate"
ForeColor="Red">*</asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QStatus" SortExpression="QStatus">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue = '<%# Bind("QStatus") %>'>
<asp:ListItem Value = " "> اختر</asp:ListItem>
<asp:ListItem Value= "مصدقه من وزاره التربيه والتعليم في بلد التخرج">مصدقه من وزاره التربيه والتعليم في بلد التخرج</asp:ListItem>
<asp:ListItem Value = "مصدقه من وزارة الخارجيه في بلد التخرج">مصدقه من وزارة الخارجيه في بلد التخرج</asp:ListItem>
<asp:ListItem Value= "مصدقه من السفاره السعوديه في بلد التخرج" >مصدقه من السفاره السعوديه في بلد التخرج</asp:ListItem>
<asp:ListItem Value= " مصدقه من الملحقيه الثقافية السعوديه في بلد التخرج" >مصدقه من الملحقيه الثقافية السعوديه في بلد التخرج</asp:ListItem>
<asp:ListItem Value = "مصدقه من الخارجية السعودية في جده">مصدقه من الخارجية السعودية في جده</asp:ListItem>
<asp:ListItem Value = "غير مصدقه">غير مصدقه</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvInsertQStaus" ValidationGroup="Update" runat="server"
ControlToValidate="DropDownList1" ErrorMessage="Please Select QStatus"
ForeColor="Red" InitialValue = "اختر">*</asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("QStatus") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlQStatus" runat="server" >
<asp:ListItem Value = " "> اختر</asp:ListItem>
<asp:ListItem Value= "مصدقه من وزاره التربيه والتعليم في بلد التخرج">مصدقه من وزاره التربيه والتعليم في بلد التخرج</asp:ListItem>
<asp:ListItem Value = "مصدقه من وزارة الخارجيه في بلد التخرج">مصدقه من وزارة الخارجيه في بلد التخرج</asp:ListItem>
<asp:ListItem Value= "مصدقه من السفاره السعوديه في بلد التخرج" >مصدقه من السفاره السعوديه في بلد التخرج</asp:ListItem>
<asp:ListItem Value= " مصدقه من الملحقيه الثقافية السعوديه في بلد التخرج" >مصدقه من الملحقيه الثقافية السعوديه في بلد التخرج</asp:ListItem>
<asp:ListItem Value = "مصدقه من الخارجية السعودية في جده">مصدقه من الخارجية السعودية في جده</asp:ListItem>
<asp:ListItem Value = "غير مصدقه">غير مصدقه</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvInsertQStatus" runat="server"
ControlToValidate="ddlQStatus" ValidationGroup="INSERT" ErrorMessage="Please Select QStatus"
ForeColor="Red">*</asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
</p>
<p>
</p>
<p>
</p>
<p>
</p>
<p>
</p>
<p>
</p>
<br />
<br />
<br />
<p>
<asp:ValidationSummary ID="ValidationSummary1" ValidationGroup="INSERT" ForeColor="Red" runat="server" />
<asp:ValidationSummary ID="ValidationSummary2" ForeColor="Red" runat="server" />
<p>
</p>
</asp:Content>
c# code
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace HR_System_v1
{
public partial class WebForm3 : System.Web.UI.Page
{
string connStr = "Data Source=ICAD-PROJ-SOFT\\SQLEXPRESS;Initial Catalog=dbHrSys;Integrated Security=True";
SqlDataAdapter sqlda = new SqlDataAdapter();
SqlCommand com = new SqlCommand();
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindgrid();
}
}
private void bindgrid()
{
SqlConnection conn = new SqlConnection(connStr);
dt = new DataTable();
com.Connection = conn;
com.CommandText = "SELECT * FROM Quali";
sqlda = new SqlDataAdapter(com);
sqlda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
TextBox txtEmpNo = (TextBox)GridView1.FooterRow.FindControl("txtEmpNo");
TextBox txtName = (TextBox)GridView1.FooterRow.FindControl("txtQName");
TextBox txtIssp = (TextBox)GridView1.FooterRow.FindControl("txtQIssP");
TextBox txtfield = (TextBox)GridView1.FooterRow.FindControl("txtField");
TextBox txtGrad = (TextBox)GridView1.FooterRow.FindControl("txtGradD");
string txtStatus = ((DropDownList)GridView1.FooterRow.FindControl("ddlQStatus")).SelectedValue;
SqlConnection conn = new SqlConnection(connStr);
com.Connection = conn;
com.CommandText = "INSERT INTO Quali (EmpNo, QName, QIssPlace, Field, GradDate,QStatus) Values ('" + txtEmpNo.Text + "','" + txtName.Text + "','" + txtIssp .Text + "','" + txtfield.Text + "','" + txtGrad.Text + "',#status)";
com.Parameters.AddWithValue("#status", txtStatus );
conn.Open();
com.ExecuteNonQuery();
Response.Write("Record inserted successfully");
bindgrid();
conn.Close();
}
else if (e.CommandName == "UpdateRow")
{
GridViewRow rowSelect = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
TextBox txtEmpNo = (TextBox)GridView1.Rows[rowindex].FindControl("txtEmpNo");
TextBox txtName = (TextBox)GridView1.Rows[rowindex].FindControl("TextBox1");
TextBox txtIssp = (TextBox)GridView1.Rows[rowindex].FindControl("TextBox2");
TextBox txtfield = (TextBox)GridView1.Rows[rowindex].FindControl("TextBox3");
TextBox txtGrad = (TextBox)GridView1.Rows[rowindex].FindControl("TextBox4");
string txtStatus = ((DropDownList)GridView1.Rows[rowindex].FindControl("DropDownList1")).SelectedValue;
SqlConnection conn = new SqlConnection(connStr);
com.Connection = conn;
com.CommandText = "Update Quali Set QName = '" + txtName.Text + "', QIssPlace='" + txtIssp .Text + "', Field='" + txtfield.Text + "',GradDate='" + txtGrad.Text + "', QStatus = #status Where EmpNo = #Empnum)";
com.Parameters.AddWithValue("#status", txtStatus );
com.Parameters.AddWithValue("#Empnum", txtEmpNo );
conn.Open();
com.ExecuteNonQuery();
Response.Write("Record updated successfully");
GridView1.EditIndex = -1;
bindgrid();
conn.Close();
}
else if (e.CommandName == "CancelUpdate")
{
GridView1.EditIndex = -1;
bindgrid();
}
else if (e.CommandName == "EditRow")
{
GridViewRow rowSelect = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
bindgrid();
}
else if (e.CommandName == "DeleteRow")
{
int qID = Convert.ToInt16(e.CommandArgument);
SqlConnection conn = new SqlConnection(connStr);
com.Connection = conn;
com.CommandText = "Delete from Quali where Qid = #qID";
com.Parameters.AddWithValue("#qID", qID );
conn.Open();
com.ExecuteNonQuery();
Response.Write("Record deleted successfully");
bindgrid();
conn.Close();
}
}
}
}

To make gridview in edit mode you need to add event rowediting
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindgrid(); // your GV bind function
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindgrid();// your GV bind function
}

code in .aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Customer.aspx.cs" Inherits="Customer.Customer" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
<script type="text/javascript">
function ConfirmationBox(username) {
var result = confirm('Are you sure you want to delete ' + username + ' Details?');
if (result) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId" runat="server"
AutoGenerateColumns="False" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="True" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
onrowupdating="gvDetails_RowUpdating"
onrowcommand="gvDetails_RowCommand">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="~/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server" ImageUrl="~/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.jpg" CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<EditItemTemplate>
<asp:TextBox ID="txtusername" runat="server" Text='<%#Eval("Username") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrusrname" runat="server"/>
<asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrcity" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<EditItemTemplate>
<asp:TextBox ID="txtDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrDesignation" runat="server"/>
<asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</div>
</form>
</body>
</html>
c# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BEL;
using BLL;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Drawing;
namespace Customer
{
public partial class Customer : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=PRASHANTH1\SQLSERVER2012;Integrated Security=true;Initial Catalog=emp");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
//string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
TextBox txtusername = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtusername");
TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtDesg");
con.Open();
SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "',UserName='" + txtusername.Text + "' where UserId=" + userid, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtusername.Text + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" + userid, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = username + " details deleted successfully";
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
TextBox txtDesgnation = (TextBox)gvDetails.FooterRow.FindControl("txtftrDesignation");
con.Open();
SqlCommand cmd =
new SqlCommand(
"insert into Employee_Details(UserName,City,Designation) values('" + txtUsrname.Text + "','" +
txtCity.Text + "','" + txtDesgnation.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtUsrname.Text + " Details not inserted";
}
}
}
}
}

Related

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

I need my code to Add and bind data to the gridview in asp web form

I don't know what's wrong with the code i've tried to search for possible reasons but haven't figured out yet what's the problem actually.Now the issue is that my web form contains a gridview in which i've place a footer row which will allow the user to add the data and that data gets added to the database and gets binded to the gridview after clicking on the insert link button,But the problem comes when i fill the data and when press link button insert it adds the data twice in gridview and in database too everytime.Below is my whole code which is performing CRUD operation on gridview:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication5.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblMessage" runat="server" ForeColor="Green" EnableViewState="false" />
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
AutoGenerateColumns="false" Width="100%" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" DataKeyNames="AutoId" OnRowDeleting="GridView1_RowDeleting" AllowPaging="true"
PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging" ShowFooter="True" OnRowCreated="GridView1_RowCreated" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" />
<asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkBtnInsert" runat="server"
CommandName="Insert">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="AutoId" DataField="AutoId" ReadOnly="true" />
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<%# Eval("FirstNAme") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<%# Eval("LastName") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<%# Eval("Age") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>' Columns="3" />
<asp:RequiredFieldValidator ID="REw" runat="server" ControlToValidate="txtAge" Text="*" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtlage" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<EditItemTemplate>
<asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active") %>'>
<asp:ListItem Text="Yes" Value="True" />
<asp:ListItem Text="No" Value="False" />
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlactive" runat="server">
<asp:ListItem Text="Yes" Value="True" Selected="True"></asp:ListItem>
<asp:ListItem Text="No" Value="False"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to delete?')">
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#efefef" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</form>
</body>
</html>
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.Configuration;
using System.Data;
namespace WebApplication5
{
public partial class WebForm2 : System.Web.UI.Page
{
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateData();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.PopulateData();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
this.PopulateData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Delete from PersonalDetail" +
" where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue(
"#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been deleted successfully !";
lblMessage.ForeColor = System.Drawing.
Color.Red;
this.PopulateData();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.PopulateData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
TextBox tFirstName = row.FindControl("txtFirstName") as TextBox;
TextBox tLastName = row.FindControl("txtLastName") as TextBox;
TextBox tAge = row.FindControl("txtAge") as TextBox;
DropDownList dropActive = row.FindControl("dropActive") as DropDownList;
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Update PersonalDetail set FirstName = #FirstName,LastName=#LastName, Age= #Age, Active = #Active" + " where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue(
"#FirstName", tFirstName.Text.Trim());
cmd.Parameters.AddWithValue(
"#LastName", tLastName.Text.Trim());
cmd.Parameters.AddWithValue(
"#Age", tAge.Text.Trim());
cmd.Parameters.AddWithValue(
"#Active", dropActive.SelectedValue);
cmd.Parameters.AddWithValue(
"#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record updated successfully !";
GridView1.EditIndex = -1;
this.PopulateData();
}
private void PopulateData()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Select * from PersonalDetail";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox1");
TextBox lname = (TextBox)GridView1.FooterRow.FindControl("txtlname");
TextBox age = (TextBox)GridView1.FooterRow.FindControl("txtlage");
DropDownList isactive = (DropDownList)GridView1.FooterRow.FindControl("ddlactive");
using(SqlConnection conn = new SqlConnection(_connStr))
{
SqlCommand cmd = new SqlCommand("INSERT INTO PersonalDetail(FirstName,LastName,Age,Active) VALUES('" + name.Text + "','" + lname.Text + "','" + age.Text + "','" + isactive.SelectedItem.Value + "')",conn);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
//int result = cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been Added successfully !";
this.PopulateData();
}
}
}
Please try below code :
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView1.RowCommand -= GridView1_RowCommand;
if (e.CommandName.Equals("Insert"))
{
TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox1");
TextBox lname = (TextBox)GridView1.FooterRow.FindControl("txtlname");
TextBox age = (TextBox)GridView1.FooterRow.FindControl("txtlage");
DropDownList isactive = (DropDownList)GridView1.FooterRow.FindControl("ddlactive");
using(SqlConnection conn = new SqlConnection(_connStr))
{
SqlCommand cmd = new SqlCommand("INSERT INTO PersonalDetail(FirstName,LastName,Age,Active) VALUES('" + name.Text + "','" + lname.Text + "','" + age.Text + "','" + isactive.SelectedItem.Value + "')",conn);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
//int result = cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been Added successfully !";
this.PopulateData();
}

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

How to delete one row in GridView with DropDownList in ASP.NET [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
This is my design page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="newsamplecomb._Default" %>
<!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="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="False"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2" OnSelectedIndexChanged="GridView1_SelectedIndexChanged1"
Height="246px" onrowdatabound="GridView1_RowDataBound" Width="1017px">
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:BoundField />
<asp:TemplateField>
<HeaderTemplate>
Rollno<br />
</HeaderTemplate>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" Height="23px" Width="73px"
AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Name
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Width="155px" ReadOnly="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
English<br />
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Height="17px" Width="103px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Tamil<br />
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Height="16px" Width="103px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Maths
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Height="16px" Width="103px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Science
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Height="16px" Width="103px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Total<br />
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Height="16px" Width="103px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Grade
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox7" runat="server" Height="16px" Width="103px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="ButtonAdd" runat="server" OnClick="ButtonAdd_Click1" Text="+" />
<asp:Button ID="Buttondel" runat="server" Text="Del"></asp:Button>
<asp:RequiredFieldValidator ID="rfv" runat="server" ErrorMessage="" ForeColor="White" ControlToValidate="TextBox1" Width="10" Display="None"></asp:RequiredFieldValidator>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
</div>
<%-- //<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ForeColor="White" ControlToValidate="TextBox1" Width="10"></asp:RequiredFieldValidator>--%>
This is my cs code
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = (DropDownList)e.Row.FindControl("DropDownList1");
string connection_string = ConfigurationManager.ConnectionStrings["DBC"].ConnectionString;
SqlConnection con = new SqlConnection(connection_string);
con.Open();
SqlCommand cmd = new SqlCommand("Select * from stud_table", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
// con.Close();
ddl.DataSource = ds;
ddl.DataTextField = "Rollno";
ddl.DataValueField = "Rollno";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("--Select--", "0"));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
dpditemdesc( sender,e);
DropDownList box1 = (DropDownList)GridView1.Rows[x].Cells[1].FindControl("DropDownList1");
if (box1.Text != "")
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridView1.Rows[i].Cells[2].Enabled = false;
GridView1.Rows[i].Cells[3].Enabled = false;
GridView1.Rows[i].Cells[4].Enabled = false;
GridView1.Rows[i].Cells[5].Enabled = false;
GridView1.Rows[i].Cells[6].Enabled = false;
GridView1.Rows[i].Cells[7].Enabled = false;
GridView1.Rows[i].Cells[8].Enabled = false;
}
}
else
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridView1.Rows[i].Cells[2].Enabled = true;
GridView1.Rows[i].Cells[3].Enabled = true;
GridView1.Rows[i].Cells[4].Enabled = true;
GridView1.Rows[i].Cells[5].Enabled = true;
GridView1.Rows[i].Cells[6].Enabled = true;
GridView1.Rows[i].Cells[7].Enabled = true;
GridView1.Rows[i].Cells[8].Enabled = true;
}
}
}
public void dpditemdesc(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.NamingContainer;
x = row.RowIndex;
TextBox box = (TextBox)GridView1.Rows[x].Cells[2].FindControl("TextBox1");
if (box.Text == "")
{
try
{
x = Convert.ToInt32(Session["ct"].ToString());
x++;
Session["ct"] = x.ToString();
}
catch
{
x = 0;
Session["ct"] = x.ToString();
}
}
if (ddl.SelectedIndex != 0)
{
string connection_string = ConfigurationManager.ConnectionStrings["DBC"].ConnectionString;
SqlConnection con = new SqlConnection(connection_string);
DropDownList box1 = (DropDownList)GridView1.Rows[x].Cells[1].FindControl("DropDownList1");
TextBox box2 = (TextBox)GridView1.Rows[x].Cells[2].FindControl("TextBox1");
TextBox box3 = (TextBox)GridView1.Rows[x].Cells[3].FindControl("TextBox2");
TextBox box4 = (TextBox)GridView1.Rows[x].Cells[4].FindControl("TextBox3");
TextBox box5 = (TextBox)GridView1.Rows[x].Cells[5].FindControl("TextBox4");
TextBox box6 = (TextBox)GridView1.Rows[x].Cells[6].FindControl("TextBox5");
TextBox box7 = (TextBox)GridView1.Rows[x].Cells[7].FindControl("TextBox6");
TextBox box8 = (TextBox)GridView1.Rows[x].Cells[8].FindControl("TextBox7");
SqlCommand cmd = new SqlCommand("select * from stud_table where Rollno='" + box1.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
box2.Text = ds.Tables[0].Rows[0][1].ToString();
box3.Text = ds.Tables[0].Rows[0][2].ToString();
box4.Text = ds.Tables[0].Rows[0][3].ToString();
box5.Text = ds.Tables[0].Rows[0][4].ToString();
box6.Text = ds.Tables[0].Rows[0][5].ToString();
box7.Text = ds.Tables[0].Rows[0][6].ToString();
box8.Text = ds.Tables[0].Rows[0][7].ToString();
}
else
{
// box.Text = "";
Response.Write("<Script>alert('Please Select Item Description')</script>");
}
}
}
}
I want to select one row and, if I click delete button, the selected row should be deleted.
Check this link
How to remove row from gridview on row command event?
Use gridview rowcommand as Rajpurohit said, then use gvYourGrid.DeleteRow(index);

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