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
Related
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();
}
I am new in asp.net development
I have created a project its working fine but i want to select the Designation from drop down but want to store the id of the designation instead of the designation
Here is my Asp.net Code for my Project
protected void BindData()
{
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "Select * from EmployeeDetails";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ADD"))
{
TextBox txtAddEmpID = (TextBox)GridView1.FooterRow.FindControl("txtAddEmpID");
TextBox txtAddName = (TextBox)GridView1.FooterRow.FindControl("txtAddName");
DropDownList ddlDesignation = (DropDownList)GridView1.FooterRow.FindControl("ddlDesignation");
TextBox txtAddCity = (TextBox)GridView1.FooterRow.FindControl("txtAddCity");
TextBox txtAddCountry = (TextBox)GridView1.FooterRow.FindControl("txtAddCountry");
conn.Open();
string cmdstr = "insert into EmployeeDetails(empid,name,designation,city,country) values(#empid,#name,#designation,#city,#country)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#empid", txtAddEmpID.Text);
cmd.Parameters.AddWithValue("#name", txtAddName.Text);
cmd.Parameters.AddWithValue("#designation", ddlDesignation.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#city", txtAddCity.Text);
cmd.Parameters.AddWithValue("#country", txtAddCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlDesignation = (DropDownList)e.Row.FindControl("ddlDesignation");
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "Select * from Designation";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
ddlDesignation.DataSource = ds.Tables[0];
ddlDesignation.DataTextField = "designation";
ddlDesignation.DataValueField = "id";
ddlDesignation.DataBind();
ddlDesignation.Items.Insert(0, new ListItem("--Select--", "0"));
this.TextBox1.Text = ddlDesignation.SelectedItem.ToString();
conn.Close();
}
}
and also this is my aspx.cs code for project
<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="false" ShowFooter="true" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_OnRowDataBound"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Employee ID">
<ItemTemplate>
<asp:Label ID="lblEmpID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "empid") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddEmpID" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:Label ID="lblDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "designation") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDesignation" runat="server" >
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "city") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCity" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "country") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCountry" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<FooterTemplate>
<asp:LinkButton ID="lbtnAdd" runat="server" CommandName="ADD" Text="Add" Width="100px"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You need to get value from SelectedValue property of dropdwon.
cmd.Parameters.AddWithValue("#designation", ddlDesignation.SelectedValue.ToString());
Did you try
var e = document.getElementById("ddlDesignation");
var strDesigId = e.options[e.selectedIndex].value;
document.getElementById("TextBox1").value = strDesigId;
I have created a gridview, for the user to add/edit and remove products. (not actually deleting but declaring it discontinued on the database)
I am getting the following exception:
An exception of type 'System.FormatException' occurred in mscorlib.dll
but was not handled in user code
My markup is as follows:
<%# Page Title="" Language="C#" MasterPageFile="~/Admin/AdminMaster.master" AutoEventWireup="true" CodeFile="addProduct.aspx.cs" Inherits="Admin_addProduct" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightCol" runat="Server">
<h1>Products</h1>
<asp:Label ID="lblProdGrd" runat="server"></asp:Label>
<asp:SqlDataSource ID="lstCatSrc" runat="server" ConnectionString='<%$ ConnectionStrings:bncConn %>' SelectCommand="SELECT CategoryName, CategoryId FROM ProductDetails.Category"></asp:SqlDataSource>
<asp:SqlDataSource ID="lstSubCatSrc" runat="server" ConnectionString='<%$ ConnectionStrings:bncConn %>' SelectCommand="SELECT ProductType, ProductTypeId FROM ProductDetails.ProductType"></asp:SqlDataSource>
<asp:SqlDataSource ID="lstImgSrc" runat="server" ConnectionString='<%$ ConnectionStrings:bncConn %>' SelectCommand="SELECT ImageName, ImageId, ImagePath FROM ProductDetails.ProductImages"></asp:SqlDataSource>
<asp:GridView
ID="grdProds"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdProds_PageIndexChanging"
OnRowCancelingEdit="grdProds_RowCancelingEdit"
OnRowCommand="grdProds_RowCommand"
OnRowEditing="grdProds_RowEditing"
OnRowUpdating="grdProds_RowUpdating"
onrowdeleting="grdProds_RowDeleting">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" FooterText="Product ID" HeaderText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" Text='<%# Eval("ProductId") %>' runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblAdd" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Name" HeaderText="Product Name" FooterText="ProductName">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("ProductName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Description" AccessibleHeaderText="Product description" FooterText="Product Description">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Text='<%# Eval("Description")%>' TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDescription" runat="server" TextMode="MultiLine"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Price" AccessibleHeaderText="Product Price" FooterText="Product Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("Price") %>' ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPrice" runat="server" Text='<%# Bind("Price") %>' TextMode="Number"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddPrice" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCat" runat="server" Text='<%# Eval("CategoryName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstCatEdit" runat="server" DataSourceID="lstCatSrc" DataTextField="CategoryName" DataValueField="CategoryId" AppendDataBoundItems="True">
<asp:ListItem Text="--(Select a category)--" Value="NULL"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstCat" runat="server" DataSourceID="lstCatSrc" DataTextField="CategoryName" DataValueField="CategoryId" AppendDataBoundItems="True">
<asp:ListItem Text="--(Select a category)--" Value="NULL"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub-Category" AccessibleHeaderText="Sub-Category" FooterText="Sub-Category">
<ItemTemplate>
<asp:Label ID="lblSubCat" runat="server" Text='<%# Eval("ProductType") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstSubCat" runat="server" DataSourceID="lstSubCatSrc" DataTextField="ProductType" DataValueField="ProductTypeId"></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddSubCat" runat="server" DataSourceID="lstSubCatSrc" DataTextField="ProductType" DataValueField="ProductTypeId"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Image" AccessibleHeaderText="Product Image" FooterText="Product Image">
<ItemTemplate>
<asp:Image ID="imgProd" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstProdImg" runat="server" DataSourceID="lstImgSrc" DataTextField="ImageName" DataValueField="ImageId"></asp:DropDownList>
<asp:Image ID="imgProdEdit" runat="server" Height="250" Width="250" />
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdImg" runat="server" DataSourceID="lstImgSrc" DataTextField="ImageName" DataValueField="ImageId"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item in stock" AccessibleHeaderText="Item in stock" FooterText="Item in stock">
<ItemTemplate>
<asp:CheckBox ID="chkInStock" runat="server" Checked='<%# Eval("InStock") %>' Enabled="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkInStockEdit" runat="server" Checked='<%# Eval("InStock") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkInStockAdd" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pre-Designed" AccessibleHeaderText="Pre-designed" FooterText="Pre-Designed">
<ItemTemplate>
<asp:CheckBox ID="chkPrePrinted" runat="server" Checked='<%# Eval("PrePrinted") %>' Enabled="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkPrePrintedEdit" runat="server" Checked='<%# Eval("PrePrinted") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkAddPrePrinted" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to declare this product Discontinued?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
My code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data.Entity;
using BillyNicClothingModel;
public partial class Admin_addProduct : System.Web.UI.Page
{
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
string CatLst;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Display";
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds, "Products");
grdProds.DataSource = ds;
grdProds.DataBind();
}
catch (Exception err)
{
lblProdGrd.Text = err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdProds.PageIndex = e.NewPageIndex;
BindGrid();
}
protected void grdProds_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdProds.EditIndex = -1;
BindGrid();
}
protected void grdProds_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
TextBox txtName = (TextBox)grdProds.FooterRow.FindControl("txtAddname");
TextBox txtDescription = (TextBox)grdProds.FooterRow.FindControl("txtAddDescription");
TextBox txtPrice = (TextBox)grdProds.FooterRow.FindControl("txtAddPrice");
DropDownList lstCatEdit = (DropDownList)grdProds.FooterRow.FindControl("lstCat");
DropDownList lstSubCat = (DropDownList)grdProds.FooterRow.FindControl("lstAddSubCat");
DropDownList lstImageProd = (DropDownList)grdProds.FooterRow.FindControl("lstAddProdImg");
CheckBox chkInStockEdit = (CheckBox)grdProds.FooterRow.FindControl("chkInStockAdd");
CheckBox chkPrePrinted = (CheckBox)grdProds.FooterRow.FindControl("chkAddPrePinted");
string ProductName, Description;
int Category, Image;
bool InStock, Preprinted;
decimal Price;
byte SubCat;
ProductName = txtName.Text;
Description = txtDescription.Text;
Price = Decimal.Parse(txtPrice.Text);
Category = int.Parse(lstCatEdit.SelectedValue);
SubCat = byte.Parse(lstSubCat.SelectedValue);
Image = int.Parse(lstImageProd.SelectedValue);
InStock = chkInStockEdit.Checked;
Preprinted = chkPrePrinted.Checked;
AddProduct(ProductName, Description, Price, Category, SubCat, Image, InStock, Preprinted);
grdProds.EditIndex = -1;
BindGrid();
}
}
protected void AddProduct(string ProductName, string Description, decimal Price, int Category, int SubCat,
int Image, bool InStock, bool Preprinted)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Add";
cmd.Parameters.Add(new SqlParameter("#ProductName", SqlDbType.VarChar, 50));
cmd.Parameters["#ProductName"].Value = ProductName;
cmd.Parameters.Add(new SqlParameter("#Description", Description));
cmd.Parameters["#Description"].Value = Description;
cmd.Parameters.Add(new SqlParameter("#Price", SqlDbType.Money));
cmd.Parameters["#Price"].Value = Price;
cmd.Parameters.Add(new SqlParameter("#Category", SqlDbType.Int));
cmd.Parameters["#Category"].Value = Category;
cmd.Parameters.Add(new SqlParameter("#ProductType", SqlDbType.TinyInt));
cmd.Parameters["#ProductType"].Value = SubCat;
cmd.Parameters.Add(new SqlParameter("#Image", SqlDbType.Int));
cmd.Parameters["#Image"].Value = Image;
cmd.Parameters.Add(new SqlParameter("#InStock", SqlDbType.Bit));
cmd.Parameters["#InStock"].Value = InStock;
cmd.Parameters.Add(new SqlParameter("#PrePrinted", SqlDbType.Bit));
cmd.Parameters["#PrePrinted"].Value = Preprinted;
try {
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text = err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label prId = (Label)grdProds.Rows[e.RowIndex].FindControl("lblProdId");
int pId = Convert.ToInt32(prId.Text);
DeleteProduct(pId);
grdProds.EditIndex = -1;
BindGrid();
}
protected void DeleteProduct(int pId)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Delete";
cmd.Parameters.Add(new SqlParameter("#ProdId", SqlDbType.Int));
cmd.Parameters["#ProdId"].Value = pId;
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_RowEditing(object sender, GridViewEditEventArgs e)
{
grdProds.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grdProds_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label prdId = (Label)grdProds.Rows[e.RowIndex].FindControl("lblProdId");
TextBox Name = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtName");
TextBox Description = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtDescription");
TextBox Price = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtPrice");
DropDownList Category = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstCatEdit");
DropDownList SubCat = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstSubCat");
DropDownList Image = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstProdImg");
CheckBox InStock = (CheckBox)grdProds.Rows[e.RowIndex].FindControl("chkInStockEdit");
CheckBox PrePrinted = (CheckBox)grdProds.Rows[e.RowIndex].FindControl("chkPrePrintedEdit");
int ProdId = Convert.ToInt32(prdId.Text);
string eName = Name.Text;
string eDescription = Description.Text;
Decimal ePrice = Convert.ToDecimal(Price.Text);
int eCat = Convert.ToInt32(Category.SelectedValue);
byte eSCat = Convert.ToByte(SubCat.SelectedValue);
int eImage = Convert.ToInt32(Image.SelectedValue);
bool eInstock = InStock.Checked;
bool ePreprinted = PrePrinted.Checked;
UpdateProduct(ProdId, eName, eDescription, ePrice, eCat, eSCat, eImage, eInstock, ePreprinted);
grdProds.EditIndex = -1;
BindGrid();
}
protected void UpdateProduct(int ProdId, string eName, string eDescription, Decimal ePrice, int eCat, byte eSCat, int eImage, bool eInstock, bool ePreprinted)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#ProdId", SqlDbType.Int));
cmd.Parameters["#ProdId"].Value = Convert.ToInt32(ProdId);
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Update";
cmd.Parameters.Add(new SqlParameter("#ProductName", SqlDbType.VarChar, 50));
cmd.Parameters["#ProductName"].Value = eName;
cmd.Parameters.Add(new SqlParameter("#Description", SqlDbType.VarChar, -1));
cmd.Parameters["#description"].Value = eDescription;
cmd.Parameters.Add(new SqlParameter("#Price", SqlDbType.Money));
cmd.Parameters["#Price"].Value = ePrice;
cmd.Parameters.Add(new SqlParameter("#Category", SqlDbType.Int));
cmd.Parameters["#Category"].Value = eCat;
cmd.Parameters.Add(new SqlParameter("#ProductType", SqlDbType.TinyInt));
cmd.Parameters["#ProductType"].Value = eSCat;
cmd.Parameters.Add(new SqlParameter("#Image", SqlDbType.Int));
cmd.Parameters["#Image"].Value = eImage;
cmd.Parameters.Add(new SqlParameter("#InStock", SqlDbType.Bit));
cmd.Parameters["#InStock"].Value = eInstock;
cmd.Parameters.Add(new SqlParameter("#PrePrinted", SqlDbType.Bit));
cmd.Parameters["#PrePrinted"].Value = ePreprinted;
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}}
My stored procedure:
CREATE PROCEDURE [ProductDetails].[bnc_Products]
-- Add the parameters for the stored procedure here
#ProdId int = 0,
#Category int = 0,
#ProductType tinyint = 0,
#Price money = 0,
#InStock bit = 1,
#ProductName varchar(50) = '',
#Image int = 0,
#Description varchar(max) = '',
#PrePrinted bit = 1,
#Discontinued bit = 0,
#Status varchar(50) = ''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
if (#Status = 'Display')
begin
select p.ProductId,p.ProductName,c.CategoryId,c.CategoryName,
pt.ProductType,pt.ProductTypeId,p.Price,p.InStock,pi.ImagePath,
pi.ImageId,pi.ImageName,p.Description,p.PrePrinted,p.Discontinued
from ProductDetails.Products p
join ProductDetails.Category c on c.CategoryId = p.Category
join ProductDetails.ProductType pt on pt.ProductTypeId = p.ProductType
join ProductDetails.ProductImages pi on pi.ImageId = p.ImageId
where p.Discontinued = 0
end
else if(#Status = 'Update')
begin
update Productdetails.Products
set Category = #Category, ProductType = #ProductType,
Price = #Price, InStock = #InStock, ProductName = #ProductName,
ImageId = #Image, Description = #Description, PrePrinted = #PrePrinted
where ProductId = #ProdId
end
else if(#Status = 'Add')
begin
insert into ProductDetails.Products
(Category,ProductType,Price,InStock,ProductName,ImageId,Description,PrePrinted,Discontinued)
values (#Category,#ProductType,#Price,#InStock,#ProductName,#Image,#Description,#PrePrinted,#Discontinued)
end
else if(#Status = 'Delete')
begin
Update ProductDetails.Products
set Discontinued = #Discontinued
where ProductId = #ProdId
end
END
Also when I try to delete a product, well declare it to be discontinued, nothing seems to happen and if anyone is able to point out where and what is wrong I would be very grateful as I am at a total loss as to what's going on. Sorry if any of this seems a little vague, I'm quite the novice at this, and so am at a complete standstill at the moment. Thank you in advanced to anyone willing to help.
You getting System.FormatException as have opened the following asp:content but have not closed it:
<asp:content id="Content3" contentplaceholderid="RightCol" runat="Server">
So after </asp:GridView> put </asp:content> and delete function will get executed.
I'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";
}
}
}
}
}
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.