cant insert foreign keys into tables - c#

im trying to insert foreign keys into table with DropDownList,
it looks good but i get this error when i press the add button
"mysql.data.mysqlclient.mysqlexception {"You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near ') values (1,1,1,1)' at line 1"}.
the tables have another Variables but now they dont Important for me and they defaults is null.
i dont have enough reputation to add image with the relationships between the tables.
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.Usage 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;
int cc = int.Parse(DDLCu.SelectedValue);
int cv = int.Parse(DDLVe.SelectedValue);
int cs = int.Parse(DDLSe.SelectedValue);
int cr = int.Parse(DDLRe.SelectedValue);
add(cc, cv, cs, cr );
BindData();
Response.Redirect("http://localhost:56717/usage.aspx");
}
private void add(int cc, int cv, int cs, int cr)
{
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
string query = "insert into tblusage(codeCust,codeVendor,codeService,codeRegion,) values (" + cc + "," + cv +"," + cs + "," + cr + ") ";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
}
}
}
}
<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>
<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>
<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>
<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("Usage") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAdd" runat="server" onclick="lnkAdd_Click">add</asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label10" runat="server" Text='<%# Eval("Usage") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Operation" ShowDeleteButton="True" />
</Columns>
</asp:GridView>

tblusage(codeCust,codeVendor,codeService,codeRegion,)
errant comma, clobber it

Related

Filtering on asp gridview headers using dropdowns on multiple columns

So I tried to added multiple filters for the gridview and I populated the dropdowns with the distinct datas of the column, but it gives me an exception, System.ArgumentException: Parameter 'siteValue' not found in the collection. I've added the mysql stored procedure along with the below code.
<asp:GridView ID="gdvTM" runat="server" AutoGenerateColumns="False" AllowPaging="true" OnPageIndexChanging="gdvTM_PageIndexChanging" DataKeyNames="ID" PageSize="10" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc" >
<Columns >
<asp:TemplateField HeaderText="Agent login">
<ItemTemplate>
<asp:Label ID="lbllogin" runat="server" Text='<%# Eval("agentlogin") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<HeaderTemplate>
Site:
<asp:DropDownList ID="ddlgvsite" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true">
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblsite" runat="server" Text='<%# Eval("site") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Skill:
<asp:DropDownList ID="ddlgvskill" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true">
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblskill" runat="server" Text='<%# Eval("skill") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift">
<ItemTemplate>
<asp:Label ID="lblshift" runat="server" Text='<%# Eval("shift") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TM">
<ItemTemplate>
<asp:Label ID="lbltm" runat="server" Text='<%# Eval("tm") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GrpM">
<ItemTemplate>
<asp:Label ID="lblGrpM" runat="server" Text='<%# Eval("grpM") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OpsM">
<ItemTemplate>
<asp:Label ID="lblOpsM" runat="server" Text='<%# Eval("opsM") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Leave type">
<ItemTemplate>
<asp:Label ID="lbltype" runat="server" Text='<%# Eval("leavetype") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate >
<asp:Label ID="lbldate" runat="server" Text='<%# Eval("date", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Time">
<ItemTemplate>
<asp:Label ID="lbltime" runat="server" Text='<%# Eval("time") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reason" ControlStyle-Width="300px">
<ItemTemplate>
<asp:Label ID="lblreason" runat="server" Text='<%# Eval("reason") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Below would be the server side codes
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindDropDownList()
{
TableCell cells = gdvTM.HeaderRow.Cells[0];
PopulateDropDown((cells.FindControl("ddlgvsite") as DropDownList), (cells.FindControl("lblsite") as Label).Text);
PopulateDropDown((cells.FindControl("ddlgvskill") as DropDownList), (cells.FindControl("lblskill") as Label).Text);
}
private void PopulateDropDown(DropDownList ddl, string columnName)
{
ddl.DataSource = BindDropDown(columnName);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please Select", "0"));
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetApprovedData");
cmd.CommandType = CommandType.StoredProcedure;
if (ViewState["Site"] != null && ViewState["Site"].ToString() != "0")
{
cmd.Parameters.AddWithValue("#siteValue", ViewState["Site"].ToString());
}
if (ViewState["Skill"] != null && ViewState["Skill"].ToString() != "0")
{
cmd.Parameters.AddWithValue("#skillValue", ViewState["Skill"].ToString());
}
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["Site"] != null ? (string)ViewState["Site"] : string.Empty, cell.FindControl("ddlgvsite") as DropDownList);
setDropdownselectedItem(ViewState["Skill"] != null ? (string)ViewState["Skill"] : string.Empty, cell.FindControl("ddlgvskill") as DropDownList);
}
private void setDropdownselectedItem(string selectedvalue, DropDownList ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
DropDownList dropdown = (DropDownList)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlgvsite":
ViewState["Site"] = selectedValue;
break;
case "ddlgvskill":
ViewState["Skill"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT " + columnName + " FROM approved WHERE " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
protected void gdvTM_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gdvTM.PageIndex = e.NewPageIndex;
this.BindGrid();
}
Below would be the MySql stored procedure
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetApprovedData`
(in siteValue varchar(45), in skillValue varchar(100))
BEGIN
select *
from approved
where site = siteValue or siteValue is null and
skill = skillValue or skillValue is null;
END
Please let me know what I'm doing wrong. Thanks in advance....
1) You have to changes your stored procedure like
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetApprovedData`(in siteValue varchar(45),
in skillValue varchar(100))
BEGIN
IF siteValue IS NULL and skillValue IS NULL THEN
select * from approved;
ELSEIF siteValue IS NULL and skillValue IS NOT NULL THEN
select * from approved where skill = skillValue;
ELSEIF siteValue IS NOT NULL and skillValue IS NULL THEN
select * from approved where site = siteValue;
ELSE
select * from approved where site = siteValue and skill = skillValue;
END IF;
END
2) In your BindGrid function make the changes below
private void BindGrid()
{
//Your rest of code is same here
string siteValue = null;
string skillValue = null;
if (ViewState["Site"] != null && ViewState["Site"].ToString() != "0")
{
siteValue = ViewState["Site"].ToString();
}
if (ViewState["Skill"] != null && ViewState["Skill"].ToString() != "0")
{
skillValue = ViewState["Skill"].ToString();
}
cmd.Parameters.AddWithValue("siteValue", siteValue);
cmd.Parameters.AddWithValue("skillValue", skillValue);
//Your rest of code is same here
}

Gridview Footer Not an Instance

I'm trying to get an Automatic ID filler for a gridview footer text box, but every time I run I get the "Not Referred Instance of an object" meaning the method isn't finding the Text box, Right?
But I have the same text box in other method and is working correctly, what its wrong?
Below is the code sample of GridView
<asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" AutoGenerateColumns="False" ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="ID UNIDAD">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddID" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UNIDAD">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNombre" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Nombre" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FRACCIONES">
<EditItemTemplate>
<asp:CheckBox ID="TextBox3" runat="server" Checked='<%# Bind("FRACCIONES") %>'></asp:CheckBox>
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkFraccion" runat="server" ></asp:CheckBox>
</FooterTemplate>
<ItemTemplate>
<asp:CheckBox ID="lbl_Fraccion" runat="server" Checked='<%# Bind("FRACCIONES") %>' ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CLAVE SAT">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtClave" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Clave" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:ImageButton ID="Agregar" runat="server" ImageUrl="~/assets/iconos/add.ico" OnClick="Agregar_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" 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" />
</asp:GridView>
Below is the code sample for binding the grid in 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.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Windows.Input;
public partial class Default2 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
string query;
string countid = " ";
SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
string connStrr = ConfigurationManager.ConnectionStrings["Integral Database"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
llenagrid();
IncrementoID();
}
public void llenagrid()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connStrr))
{
string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
IncrementoID();
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void Agregar_Click(object sender, ImageClickEventArgs e)
{
connStr.Open();
GridViewRow row = GridView1.FooterRow;
TextBox txtNombre = (TextBox)row.FindControl("txtNombre");
string str = "select count(nombre) from unidades where nombre like '"+txtNombre.Text+ "'";
SqlCommand com = new SqlCommand(str,connStr);
int count = Convert.ToInt32(com.ExecuteScalar());
connStr.Close();
if (count > 0)
{
string script = "alert('Este Nombre ya Existe.','AtenciĆ³n');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "testScript", script, true);
}
else
{
connStr.Open();
TextBox txtID = (TextBox)row.FindControl("txtAddID");
CheckBox chkFracc = (CheckBox)row.FindControl("chkFraccion");
TextBox txtClave = (TextBox)row.FindControl("txtClave");
string ID = txtID.Text;
string Nombre = txtNombre.Text;
bool Fracc = chkFracc.Checked;
string clave = txtClave.Text;
string query2 = "Insert into unidades values('" + ID + "','" + Nombre + "','" + Fracc + "','" + clave + "')";
SqlCommand cmd2 = new SqlCommand(query2, connStr);
cmd2.ExecuteNonQuery();
connStr.Close();
llenagrid();
IncrementoID();
}
}
public void IncrementoID()
{
//query = "select Count(id_unidad) from unidades";
//con.Open();
//SqlCommand cmd = new SqlCommand(query, con);
//string cid = cmd.ExecuteScalar().ToString();
//con.Close();
//TextBox ID = (TextBox)GridView1.FooterRow.FindControl("txtAddID");
//ID.Text = countid + (int.Parse(cid) + 1);
//ID.ReadOnly = true;
con.Open();
SqlCommand cmd = new SqlCommand("select MAX (CAST( ID_UNIDAD as INT)) from unidades",con);
SqlDataReader rd = cmd.ExecuteReader();
TextBox txtID = ((TextBox)GridView1.FooterRow.FindControl("txtAddID"));
if (rd.Read())
{
string Value = rd[0].ToString();
if (Value == "")
{
txtID.Text = "1";
}
else
{
txtID.Text = rd[0].ToString();
txtID.Text = (Convert.ToInt64(txtID.Text) + 1).ToString();
}
}
con.Close();
}
}
As you can see, in the insert method it finds the gridview textbox (txtAddID) and when I try to use the same exact syntax in the IncrementoID Method it doesn't work.
Here is the problem in the method llenagrid(), before binding GridView you are trying to access the control that are in Gridview (inside method IncrementoID), So it's giving error as Not Referred Instance of an object means the Object you are trying to access is not yet referenced. Below code sample can help you out:
public void llenagrid()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connStrr))
{
string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
//IncrementoID(); // Remove the function call from here
GridView1.DataSource = table;
GridView1.DataBind();
IncrementoID(); // Call the function after GridView got binded.
}

how to CRUD operation in gridview using 3 tier

I am using n tier architecture
Here is my aspx.cs code
using System;
using System.Web.UI;
using BAL;
using System.Web.UI.WebControls;
namespace GridViewThreeTierApplication
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
var dataSource = new DAL.dal().GetAllCustomers();
if (dataSource != null)
{
GridView1.DataSource = dataSource;
GridView1.DataBind();
}
}
protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Control control = e.Row.Cells[0].Controls[0];
if (control is LinkButton)
{
int num = Convert.ToInt32(e.Row.RowIndex);
bal.DeleteCustomers(num);
}
}
}
}
}
here is my markup
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="GridViewThreeTierApplication.index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True" OnDataBound="GridView1_DataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="LinkButton1" runat="server" Text="Update" CommandName="Update" CausesValidation="true" />
<asp:Button ID="LinkButton2" runat="server" Text="Cancel" CausesValidation="false" CommandName="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CustomerID" SortExpression="CustomerID">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("CustomerID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("CustomerID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="InsertBtn" runat="server" Text="Insert" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName" SortExpression="LastName">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFiname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email" SortExpression="Email">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Email") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PhoneNumber" SortExpression="PhoneNumber">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("PhoneNumber") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("PhoneNumber") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFirname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
</div>
</form>
</body>
</html>
here is my data access layer
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;
namespace DAL
{
public class dal
{
public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int PhoneNumber { get; set; }
}
public List<Customer> GetAllCustomers()
{
List<Customer> listCustomers = new List<Customer>();
string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("Select * from Customer", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Customer Customer = new Customer();
Customer.CustomerID = Convert.ToInt32(rdr["CustomerID"]);
Customer.FirstName = rdr["FirstName"].ToString();
Customer.LastName = rdr["LastName"].ToString();
Customer.Email = rdr["Email"].ToString();
Customer.PhoneNumber = Convert.ToInt32(rdr["PhoneNumber"]);
listCustomers.Add(Customer);
}
}
return listCustomers;
}
}
}
here is my business object
using System.Configuration;
using System.Data.SqlClient;
namespace BAL
{
public class bal
{
protected void GetALLCustomer()
{
}
public static void DeleteCustomers(int CustomerID)
{
string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand ("Delete from Customer where CustomerID = #CustomerID", con);
SqlParameter param = new SqlParameter("#CustomerId", CustomerID);
cmd.Parameters.Add(param);
con.Open();
cmd.ExecuteNonQuery();
}
}
public static int InsertCustomers(string FirstName, string LastName, string Email, int PhoneNumber)
{
string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string updateQuery = "Insert into Customers (FirstName, LastName, Email,PhoneNumber)" +
" values (#FirstName, #LastName, #Email,#PhoneNumber)";
SqlCommand cmd = new SqlCommand(updateQuery, con);
SqlParameter paramFirstName = new SqlParameter("#FirstName", FirstName);
cmd.Parameters.Add(paramFirstName);
SqlParameter paramLastName = new SqlParameter("#LastName", LastName);
cmd.Parameters.Add(paramLastName);
SqlParameter paramEmail = new SqlParameter("#Email", Email);
cmd.Parameters.Add(paramEmail);
SqlParameter paramPhoneNumber = new SqlParameter("#PhoneNumber", PhoneNumber);
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
}
I am able to perform select query .
I can not perform Create ,Delete or Update .
It seems like the phone number parameter is not on the cmd command
Here is how i got it to work
1) First i deleted event GridView1_DataBound
Delete "CommandField" column from GridView1 (markup)
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
2) insert this markup in its place
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbEdit" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="EditRow" ForeColor="#8C4510" runat="server">Edit</asp:LinkButton>
<asp:LinkButton ID="lbDelete" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="DeleteRow" ForeColor="#8C4510" runat="server" CausesValidation="false">Delete</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lbUpdate" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="UpdateRow" ForeColor="#8C4510" runat="server">Update</asp:LinkButton>
<asp:LinkButton ID="lbCancel" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="CancelUpdate" ForeColor="#8C4510" runat="server" CausesValidation="false">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
3) insert this FooterTemplate of EmployeeId
Insert
4) Now generate GridView1_RowCommand() event handler method.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditRow")
{
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
GridView1.EditIndex = rowIndex;
BindGrid();
}
else if (e.CommandName == "DeleteRow")
{
BAL.bal.DeleteCustomers(Convert.ToInt32(e.CommandArgument));
BindGrid();
}
else if (e.CommandName == "CancelUpdate")
{
GridView1.EditIndex = -1;
BindGrid();
}
else if (e.CommandName == "UpdateRow")
{
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
int CustomerId = Convert.ToInt32(e.CommandArgument);
string Name = ((TextBox)GridView1.Rows[rowIndex].FindControl("TextBox1")).Text;
string Gender = ((DropDownList)GridView1.Rows[rowIndex].FindControl("DropDownList1")).SelectedValue;
string City = ((TextBox)GridView1.Rows[rowIndex].FindControl("TextBox3")).Text;
BAL.bal.UpdateCustomers(CustomerId, Name, Gender, City);
GridView1.EditIndex = -1;
BindGrid();
}
else if (e.CommandName == "InsertRow")
{
string Name = ((TextBox)GridView1.FooterRow.FindControl("txtName")).Text;
string Gender = ((DropDownList)GridView1.FooterRow.FindControl("ddlGender")).SelectedValue;
string City = ((TextBox)GridView1.FooterRow.FindControl("txtCity")).Text;
BAL.bal.InsertCustomers(name, gender, city);
BindGrid();
}
}
6) Correct insertCustomer Method
public static int InsertCustomers(string Name, string Gender, string City)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string updateQuery = "Insert into tblEmployee (Name, Gender, City)" +
" values (#Name, #Gender, #City)";
SqlCommand cmd = new SqlCommand(updateQuery, con);
SqlParameter paramName = new SqlParameter("#Name", Name);
cmd.Parameters.Add(paramName);
SqlParameter paramGender = new SqlParameter("#Gender", Gender);
cmd.Parameters.Add(paramGender);
SqlParameter paramCity = new SqlParameter("#City", City);
cmd.Parameters.Add(paramCity);
con.Open();
return cmd.ExecuteNonQuery();
}
}
If you want to show a confirmation dialog box, before a row is deleted, include javascript confirm() function, using "OnClientClick" attribute of LinkButton "lbDelete".
<asp:LinkButton ID="lbDelete" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="DeleteRow" ForeColor="#8C4510" runat="server" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this row');">Delete</asp:LinkButton>

how to hide templatefield in gridview

I am repeating this question because i am not able to find answer from anywhere.
I Have a GridView in .aspx page. I want to hide columns based on aspx.cs BindData() method.
I have tried using below code but not able to hide. I am using Asp.net with C#.
Below is my GridView with columns and I have also included the Button click code.
If I select "T-L" which is in below else-if Ladder i am getting this error
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'tutorial'.
I have marked a test case error in .aspx
For temporary to make my program work i am using 4 gridview to bind 4 query,which is not feasible...How can i hide templatefield invisible based on conditions...
plz help me..
<GridView>
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" SortExpression="id"
Visible="false" />
<asp:TemplateField HeaderText="RollNo" >
<ItemTemplate>
<%# Eval("st_rollno")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbsturollno" runat="Server"
Text='<%# Eval("st_rollno") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("st_name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbstuname" runat="Server"
Text='<%# Eval("st_name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Theory">
<ItemTemplate>
<%# Eval("theory")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtheory" runat="Server"
Text='<%# Eval("theory") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("ttotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtheorytotal" runat="Server"
Text='<%# Eval("ttotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lab" >
<ItemTemplate>
<%# Eval("lab")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tblab" runat="Server"
Text='<%# Eval("lab") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("ltotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tblabtotal" runat="Server"
Text='<%# Eval("ltotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tutorial" >
<ItemTemplate>
*Error is HERE <%# Eval("tutorial")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtutorial" runat="Server"
Text='<%# Eval("tutorial") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("tutotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtutorialtotal" runat="Server"
Text='<%# Eval("tutotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</GridView>
private void BindData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
if (stype.Equals("L"))
{
query = "SELECT [id], [st_rollno], [st_name], [lab], [ltotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
GridView1.Columns[3].Visible = false;
GridView1.Columns[4].Visible = false;
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
}
else if (stype.Equals("T"))
{
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
GridView1.Columns[5].Visible = false;
GridView1.Columns[6].Visible = false;
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
}
else if (stype.Equals("T-L"))
{
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal], [lab], [ltotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
}
else
{
query = "SELECT [id], [st_rollno], [st_name],[theory], [ttotal], [lab], [ltotal], [tutorial], [tutotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
}
com = new SqlCommand(query);
com.Parameters.Add("#branch_name", dept);
com.Parameters.Add("#scode", dpsubject.SelectedItem.Text.ToString());
com.Parameters.Add("#sem_no", Int32.Parse(dpsemno.SelectedItem.Text.ToString()));
com.Parameters.Add("#sess_no",Int32.Parse(dpsessional.SelectedItem.Text.ToString()));
using (SqlDataAdapter sda = new SqlDataAdapter())
{
com.Connection = con;
con.Open();
sda.SelectCommand = com;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
}
}
protected void bsubmit_Click(object sender, EventArgs e)
{
this.BindData();
}
Try having your query still return a result for each column you want to hide even though you won't use those values. In the query for when stype is "T-L", change query from this:
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal], [lab], [ltotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
To this:
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal], [lab], [ltotal], '' as tutorial, '' as tutotal FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
EDIT:
To hide the column, add the following method to your code behind:
protected void GridView_DataBound(object sender, GridViewRowEventArgs e)
{
if (stype.Equals("T-L"))
{
MyGridView.Columns[7].Visible = false;
MyGridView.Columns[8].Visible = false;
}
}
And subscribe to the DataBound event on the GridView. Notice that I added an ID to the GridView so I can reference it from the code behind.
<GridView ID="MyGridView" OnDataBound="GridView_DataBound">

Grid Showing old values after updation using ObjectDataSource to bind and Update the grid

I am using ObjectDataSource to Bind and update the grid .It is working fine and the records are updating in the database but after updating ,it is still showing the same records in the grid (Previous Values). Please help me that what i will do so that after database updation, The grid will display updated records ,not the old records.Please modify my code also in case if any one found the solution.
Thanks in Advance.
Please find the code below.
GridView Code:-
<asp:Panel ID="pnlGrdShift" runat="server" ScrollBars="Auto" Width="900px" Height="520px" CssClass="srcColor">
<cc1:GridView ID="gvShift" runat="server" AutoGenerateColumns="False" AllowSorting="True"
CssClass="grid"
OnDataBound="gvShift_DataBound"
DataSourceID="odsShiftDetails"
AllowPaging="True"
ShowFooter="false"
onrowcancelingedit="gvShift_RowCancelingEdit"
onrowcommand="gvShift_RowCommand"
onrowdeleting="gvShift_RowDeleting"
onrowediting="gvShift_RowEditing"
onrowupdating="gvShift_RowUpdating"
OnSelectedIndexChanged="gvShift_SelectedIndexChanged"
OnRowDataBound="gvShift_RowDataBound">
<AlternatingRowStyle CssClass="altrowstyle" />
<HeaderStyle CssClass="headerstyle" />
<RowStyle CssClass="rowstyle" Wrap="false" />
<EmptyDataRowStyle BackColor="#edf5ff" Height="300px" VerticalAlign="Middle" HorizontalAlign="Center" />
<EmptyDataTemplate >
No Records Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="E Code" SortExpression="userecode" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblUserECode" runat="server" Text='<%#Eval("userecode") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditUserECode" runat="server" Text='<%#Eval("userecode") %>' style="width:50px;" CssClass="GridContent" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Name" SortExpression="username" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblUserName" runat="server" Text='<%#Eval("username") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditUserName" runat="server" Text='<%#Eval("username") %>' style="width:100px;" CssClass="GridContent"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift Start Time" SortExpression="ShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>' CssClass="GridContent"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftStartTime" runat="server" ControlToValidate="ddlShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift End Time" SortExpression="ShiftEndTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftEndTime" runat="server" ControlToValidate="ddlShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="ShiftEndTIme" HeaderText="Shift End Time" SortExpression="ShiftEndTIme"/>--%>
<asp:TemplateField HeaderText="Saturday Shift Start Time" SortExpression="WeekendShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftStartTime" runat="server" ControlToValidate="ddlWeekendShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Saturday Shift End Time" SortExpression="weekendshiftendtime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' CssClass="GridContent"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftEndTime" runat="server" ControlToValidate="ddlWeekendShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" >
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update" ForeColor="White"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" ForeColor="White"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" ForeColor="White"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerTemplate >
<table width="100%" >
<tr>
<td style="text-align: left">
Page Size:
<asp:DropDownList ID="ddPageSize" runat="server" EnableViewState="true" OnSelectedIndexChanged="ddPageSize_SelectedIndexChanged" AutoPostBack="true" style="width:50px;">
<asp:ListItem Text="10" ></asp:ListItem>
<asp:ListItem Text="20" ></asp:ListItem>
<asp:ListItem Text="30" ></asp:ListItem>
<asp:ListItem Text="40" ></asp:ListItem>
<asp:ListItem Text="50" ></asp:ListItem>
</asp:DropDownList>
</td>
<td style="text-align: right">
<asp:Label ID="lblPageCount" runat="server"></asp:Label>
</td>
</tr>
</table>
</PagerTemplate>
</cc1:GridView>
</asp:Panel>
<asp:ObjectDataSource ID="odsShiftDetails" runat="server"
SelectMethod="GetShiftInfoSortedPage" TypeName="EQ.DAL.ShiftInfoDB"
EnablePaging="True" SelectCountMethod="GetShiftInfoCount"
SortParameterName="sortExpression" UpdateMethod="UpdateShift">
<UpdateParameters>
<asp:Parameter Name="sql"/>
</UpdateParameters>
<SelectParameters>
<asp:ControlParameter ControlID="hfSearchCriteria" Name="searchCriteria" Direction="Input" />
</SelectParameters>
</asp:ObjectDataSource>
Code Behind for Update:-
protected void gvShift_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftStartTime");
TextBox txtShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftEndTime");
TextBox txtWeekendShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftStartTime");
TextBox txtWeekendShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftEndTime");
Label lblUserecode = (Label)gvShift.Rows[e.RowIndex].FindControl("lblEditUserECode");
string userecode = lblUserecode.Text.ToString();
string _ShiftStart = txtShiftStartTime.Text.ToString();
string _ShiftEnd = txtShiftEndTime.Text.ToString();
string _WeekendShiftStart = txtWeekendShiftStartTime.Text.ToString();
string _WeekendShiftend = txtWeekendShiftEndTime.Text.ToString();
EmployeeQuotientCL.Entities.ConfigurationVariables _configVariables = new ConfigurationVariables();
string databaseConnectionString = _configVariables.ConnectionString;
SqlConnection sqlConnection = null;
if (((databaseConnectionString + string.Empty) != string.Empty))
{
DBConnect dbConnect = new DBConnect(_configVariables.ConnectionString);
sqlConnection = dbConnect.SQLConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConnection;
string sql=null;
cmd.CommandText = "UPDATE UserInfo SET ShiftStartTime ='" + _ShiftStart + "',ShiftEndTime='" + _ShiftEnd.ToString() + "',Weekendshiftstarttime='" + _WeekendShiftStart.ToString() + "',Weekendshiftendtime='" + _WeekendShiftend.ToString() + "' WHERE UserECode=" + userecode.ToString();
odsShiftDetails.UpdateParameters["sql"].DefaultValue = cmd.CommandText;
odsShiftDetails.Update();
}
}
catch (Exception ex)
{
}
}
ShiftInfoDBCache.cs
public class ShiftInfoDB
{
private const string SHIFTINFO_CACHE_KEY = "SHIFTINFO_DATA";
private const string SHIFTINFOCOUNT_CACHE_KEY = "SHIFTINFO_COUNT";
static EmployeeQuotientCL.Entities.ConfigurationVariables _config = new EmployeeQuotientCL.Entities.ConfigurationVariables();
static int _SupervisorecodeforShift;
public static DataTable GetShiftInfoSortedPage(int maximumRows, int startRowIndex, string sortExpression, string searchCriteria)
{
_SupervisorecodeforShift=EmployeeQuotientCL.Entities.StaticGlobalValue.UserId;
if (string.IsNullOrEmpty(sortExpression))
sortExpression = "userecode";
try
{
if (ShiftInfoDBCache.isRecordsCached(SHIFTINFO_CACHE_KEY))
return ShiftInfoDBCache.GetData(SHIFTINFO_CACHE_KEY, startRowIndex + 1, maximumRows, sortExpression, searchCriteria);
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
string sql = "select distinct MP.userecode,UI.username,UI.ShiftStartTime,UI.ShiftEndTime,UI.WeekendShiftStartTime,UI.weekendshiftendtime from AssociateSupervisorMapping MP inner join UserInfo UI on MP.Userecode=UI.Userecode where supervisorecode=" + _SupervisorecodeforShift.ToString();
SqlCommand custCommand = new SqlCommand(sql, dbConnection);
custCommand.CommandType = CommandType.Text;
SqlDataAdapter ad = new SqlDataAdapter(custCommand);
DataTable dtCustomers = new DataTable();
ad.Fill(dtCustomers);
dbConnection.Close();
//Cache records
ShiftInfoDBCache.Add(SHIFTINFO_CACHE_KEY, dtCustomers);
}
catch (Exception e)
{
throw;
}
return ShiftInfoDBCache.GetData(SHIFTINFO_CACHE_KEY, startRowIndex + 1, maximumRows, sortExpression, null);
}
public static int GetShiftInfoCount(string searchCriteria)
{
_SupervisorecodeforShift=EmployeeQuotientCL.Entities.StaticGlobalValue.UserId;
int custCount = 0;
try
{
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
string sql = "select Count(*)from (select distinct MP.userecode,UI.username,UI.ShiftStartTime,UI.ShiftEndTime,UI.WeekendShiftStartTime,UI.weekendshiftendtime from AssociateSupervisorMapping MP inner join UserInfo UI on MP.Userecode=UI.Userecode where supervisorecode="+_SupervisorecodeforShift.ToString()+")AS internalQuery";
if (!string.IsNullOrEmpty(searchCriteria))
sql = sql + " where " + searchCriteria;
SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
sqlCommand.Connection = dbConnection;
dbConnection.Open();
sqlCommand.CommandType = CommandType.Text;
custCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
dbConnection.Close();
if (ShiftInfoDBCache.Get(SHIFTINFOCOUNT_CACHE_KEY) != null)
{
// remove customers data if customers count has changed since first cache
if (Convert.ToInt32(ShiftInfoDBCache.Get(SHIFTINFOCOUNT_CACHE_KEY)) != custCount && string.IsNullOrEmpty(searchCriteria))
{
ShiftInfoDBCache.Remove(SHIFTINFO_CACHE_KEY);
}
}
if (string.IsNullOrEmpty(searchCriteria))
ShiftInfoDBCache.Add(SHIFTINFOCOUNT_CACHE_KEY, custCount);
}
catch (Exception e)
{
throw;
}
return custCount;
}
public static void UpdateShift(string sql)
{
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
sqlCommand.CommandType=CommandType.Text;
sqlCommand.CommandText=sql;
dbConnection.Open();
sqlCommand.Connection = dbConnection;
//sqlCommand.CommandType = CommandType.Text;
sqlCommand.ExecuteNonQuery();
dbConnection.Close();
}
}
ShiftInfoDBCache.cs
public class ShiftInfoDBCache
{
public static bool isRecordsCached(string cacheKey)
{
Cache dbCache = HttpContext.Current.Cache;
if (dbCache[cacheKey] == null)
return false;
return true;
}
public static void Add(string key, object value)
{
Cache dbCache = HttpContext.Current.Cache;
dbCache.Add(key, value, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
}
public static object Get(string key)
{
Cache dbCache = HttpContext.Current.Cache;
return dbCache[key];
}
public static object Remove(string key)
{
Cache dbCache = HttpContext.Current.Cache;
return dbCache.Remove(key);
}
public static DataTable GetData(string cacheKey, int startRowIndex, int maximumRowNumber, string sortExpression, string searchCriteria)
{
Cache dbCache = HttpContext.Current.Cache;
if (dbCache[cacheKey] != null)
{
DataTable dtble = dbCache[cacheKey] as DataTable;
DataTable dtblNew = dtble.Clone();
DataRow[] rows = dtble.Select(searchCriteria, sortExpression);
if (rows != null)
{
if (rows.Count() > 0)
{
if (startRowIndex > rows.Count())
{
startRowIndex = rows.Count() - maximumRowNumber;
if (startRowIndex < 0)
{
startRowIndex = 1;
maximumRowNumber = rows.Count();
}
}
for (int i = startRowIndex - 1; i < (startRowIndex + maximumRowNumber - 1); i++)
{
if (i < rows.Count())
dtblNew.ImportRow(rows[i]);
}
return dtblNew;
}
}
return dtblNew;
}
return null;
}
}
public static void UpdateShift(string sql)
{
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
sqlCommand.CommandType=CommandType.Text;
sqlCommand.CommandText=sql;
dbConnection.Open();
sqlCommand.Connection = dbConnection;
//sqlCommand.CommandType = CommandType.Text;
sqlCommand.ExecuteNonQuery();
dbConnection.Close();
ShiftInfoDBCache.Remove(SHIFTINFO_CACHE_KEY);
}
Modifying UpdateShift Method in ShiftInfoDB.cs fixed my issue.

Categories