I have recently been involved in a mini-project and am trying to use asp.net with SQL in it. The problem I am facing is that the insert function is not working although the edit and delete are working perfectly fine on the same page. This is the home2.aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Home2.aspx.cs" Inherits="DBPROJECT.Home2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="background-image:url(img1.jpg)" >
<form id="form2" runat="server">
<asp:GridView ID="ab" runat="server" Font-Names="Arial"
HorizontalAlign="Center" BackColor="White" BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px"
CellPadding="4" AutoGenerateColumns="False"
OnRowEditing="ab_RowEditing" OnRowCancelingEdit="ab_RowCancelingEdit"
OnRowDeleting="ab_RowDeleting" OnRowUpdating="ab_RowUpdating"
EnableViewState="False" ><AlternatingRowStyle HorizontalAlign="Center" />
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
<asp:TemplateField HeaderText="Registration Number" HeaderStyle-
HorizontalAlign="Left">
<EditItemTemplate>
<asp:Label ID="aa" runat="server" Text='<%# Bind("reg_no") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblItemNo" runat="server" Text='<%# Bind("reg_no") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name Of NGO" HeaderStyle-
HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="bb" runat="server" Text='<%# Bind("nname") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblItemName" runat="server" Text='<%# Bind("nname") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="cc" runat="server" Text='<%# Bind("address") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblTotalUnits" runat="server" Text='<%# Bind("address") %>'>
</asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="OwnerID" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:Label ID="dd" runat="server" Text='<%# Bind("owner_id") %>'>
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblItemNoo" runat="server" Text='<%# Bind("owner_id") %>'>
</asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
</Columns>
<EditRowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<EmptyDataRowStyle HorizontalAlign="Center" />
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle Font-Bold="True" BackColor="#990000" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<RowStyle HorizontalAlign="Center" BackColor="White" ForeColor="#330099" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
</asp:GridView>
<br />
<asp:Label runat="server" text="Enter the registration number" Font-Bold="True" ForeColor="White" BackColor="Black"></asp:Label>
<asp:TextBox runat="server" ID="A1" ></asp:TextBox>
<br />
<br />
<asp:Label runat="server" text="Enter the name of NGO " Font-Bold="True"
ForeColor="White" BackColor="Black"></asp:Label>
<asp:TextBox runat="server" ID="A2" ></asp:TextBox>
<br />
<br />
<asp:Label runat="server" text="Enter the address " Font-Bold="True"
ForeColor="White" BackColor="Black"></asp:Label>
<asp:TextBox runat="server" ID="A3" ></asp:TextBox>
<br />
<br />
<asp:Label runat="server" text="Enter the owner's ID " Font-Bold="True"
ForeColor="White" BackColor="Black"></asp:Label>
<asp:TextBox runat="server" ID="A4" ></asp:TextBox>
<br />
<br />
<div>
<asp:Button runat="server" Text="Insert" ID="Button1"OnClick="Button1_Click"
BackColor="White" Font-Bold="True" Font-Size="Large" ForeColor="Maroon"/>
</div>
</form>
</body>
</html>
This is the aspx.cs file
using System;
using System.Collections;
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;
using DBPROJECT.DAL;
namespace DBPROJECT
{
public partial class Home2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoadGrid();
}
public void LoadGrid()
{
myDAL objMyDal = new myDAL();
ab.DataSource = objMyDal.SelectItem();
ab.DataBind();
}
protected void ab_RowEditing(object sender, GridViewEditEventArgs e)
{
ab.EditIndex = e.NewEditIndex;
LoadGrid();
}
protected void ab_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)ab.Rows[e.RowIndex];
Label a1 = (Label)ab.Rows[e.RowIndex].FindControl("aa");
TextBox a2 = (TextBox)ab.Rows[e.RowIndex].FindControl("bb");
TextBox a3 = (TextBox)ab.Rows[e.RowIndex].FindControl("cc");
Label a4 = (Label)ab.Rows[e.RowIndex].FindControl("dd");
int reg_no = Convert.ToInt32(a1.Text.ToString());
string nname = a2.Text.ToString();
string address = a3.Text.ToString();
int owner1 = Convert.ToInt32(a4.Text.ToString());
myDAL objMyDal = new myDAL();
objMyDal.UpdateItem(reg_no, nname, address);
// ======================================================
ab.EditIndex = -1;
LoadGrid();
}
protected void ab_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
myDAL objMyDal = new myDAL();
GridViewRow row = ab.Rows[e.RowIndex];
Label itemLabel = (Label)row.FindControl("lblItemNo");
int ItemID = Convert.ToInt32(itemLabel.Text.ToString());
int result = objMyDal.DeleteItem(ItemID);
if (result == -1)
{
ab.DataSource = objMyDal.SelectItem();
ab.DataBind();
}
else
{
string message = "No row deleted";
ClientScript.RegisterOnSubmitStatement(this.GetType(),"alert", message.ToString());
}
}
protected void ab_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
ab.EditIndex = -1;
LoadGrid();
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable DT = new DataTable();
int aa= Convert.ToInt32(A1.Text.ToString());
string bb = A2.Text.ToString();
string cc = A3.Text.ToString();
int dd = Convert.ToInt32(A4.Text.ToString());
Response.Write("<script>alert('Insert failed');</script>");
myDAL objMyDal = new myDAL();
objMyDal.insertItem(aa,bb,cc,dd,ref DT);
LoadGrid();
}
}
}
The definition in the dal file is as follows
public int insertItem(int reg, string name, string add, int o1, ref DataTable DT)
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd,cmd1;
int result = 0;
try
{
//cmd1 = new SqlCommand("newNGO", con);
cmd = new SqlCommand("insert into NGO values (#reg_no,#nname,#address,#owner_id)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#reg_no", SqlDbType.Int).Value = reg;
cmd.Parameters.Add("#nname", SqlDbType.VarChar).Value = name;
cmd.Parameters.Add("#address", SqlDbType.VarChar).Value = add;
cmd.Parameters.Add("#owner_id", SqlDbType.Int).Value = o1;
/*
cmd1.Parameters.Add("#nname", SqlDbType.VarChar).Value = name;
cmd1.Parameters.Add("#address", SqlDbType.VarChar).Value = add;
cmd1.Parameters.Add("#owner_id", SqlDbType.Int).Value = o1;
*/
result = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine("SQL Error" + ex.Message.ToString());
}
finally
{
con.Close();
}
return result;
}
The column names of the table are reg_no (int), nname(varchar), address(varchar) and owner_id(int). reg_no is the primary key and owner_id is foreign key.
I have been trying to find out the error since last week. Clicking the insert button does not throw any exception or error but it also does not insert the values in the database.
change cmd.Parameters.Add to cmd.Parameters.AddWithValue and then try
I think I have figured it out. The variable nname was set as varchar(20) and I was entering a string "Doctors without Borders" which is clearly larger than 20 and therefore it was throwing the exception. Thanks for your help and concerns.
Related
I am trying to hide the Edit button when a student logs in and show it when the admin logs in. By default the edit button is visible. I want to hide the edit button on Page_Load. I have tried wrapping it in a div but it does not work for some reason. Any solutions??
GRIDVIEW CODE FOR .ASPX FILE:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" Width="1224px" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%#Eval("SrNo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Name" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Profile">
<ItemTemplate>
<asp:Label ID="lbl_Profile" runat="server" Text='<%#Eval("Profile") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Profile" runat="server" Text='<%#Eval("Profile") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CTC">
<ItemTemplate>
<asp:Label ID="lbl_CTC" runat="server" Text='<%#Eval("CTC") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_CTC" runat="server" Text='<%#Eval("CTC") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="InterOrFT">
<ItemTemplate>
<asp:Label ID="lbl_InternOrFT" runat="server" Text='<%#Eval("InternOrFT") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_InternOrFT" runat="server" Text='<%#Eval("InternOrFT") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lbl_Location" runat="server" Text='<%#Eval("Location") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Location" runat="server" Text='<%#Eval("Location") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
CODE FOR .ASPX.CS FILE:
protected void Page_Load(object sender, EventArgs e)
{
if(Session["user"] == null)
{
Response.Redirect("~/login.aspx");
}
else
{
if (Session["user"].ToString() != "admin")
{
addForm.Visible = false;
}
}
linkProfile.Text = Session["user"].ToString();
if (!IsPostBack)
{
GVBind();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cs);
con.Open();
SqlCommand cmd = new SqlCommand("insert into tblUpcoming values(#name, #profile, #ctc, #internFT, #location)", con);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#profile", txtProfile.Text);
cmd.Parameters.AddWithValue("#ctc", txtCTC.Text);
cmd.Parameters.AddWithValue("#internFT", txtInternFT.Text);
cmd.Parameters.AddWithValue("#location", txtLocation.Text);
cmd.ExecuteNonQuery();
con.Close();
GVBind();
clear();
}
void GVBind()
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("select compID as SrNo, name as Name, profile as Profile, internFT as InternOrFT, ctc as CTC, location as Location from tblUpcoming", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Read the session value directly at the aspx-file
<asp:Button ID="btn_Edit" runat="server" Text="Edit"
CommandName="Edit" Visible='<% Session["user"] == "admin" %>' />
also see ASP.NET "special" tags
I've got a GridView which has OnRowEditing, UnRowUpdating and OnRowDeleting buttons. Now we want to let users add a new record. So currently I have this:
<asp:Panel runat="server" ID="ShowDiv1" Visible="false" BorderStyle="Solid" BorderWidth="0" Width="440px">
<asp:Label ID="lblShowDiv1Title" runat="server" Text="Executive Review Leads" Font-Bold="true"></asp:Label>
<br />
<div id="divGrid" style='width:450px; overflow:auto'>
<asp:GridView ID="DataGrid_Leads" runat="server"
AutoGenerateColumns="False"
ShowFooter="true"
CellPadding="1"
CssClass="hoverTable"
DataKeyNames="LOOKUP_VALUE"
OnRowCancelingEdit="DataGrid_Leads_CancelCommand"
OnRowEditing="DataGrid_Leads_EditCommand"
OnRowDeleting="DataGrid_Leads_DeleteCommand"
OnRowUpdating="DataGrid_Leads_UpdateCommand">
<Columns>
<asp:TemplateField HeaderText="Lead" ItemStyle-Width="230px">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Width="220px" Text='<%#Eval("LOOKUP_DESCRIPTION") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Name" runat="server" Width="220px" Text='<%#Eval("LOOKUP_DESCRIPTION") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ntxt_Name" runat="server" Width="220px" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="90px">
<ItemTemplate>
<asp:Button ID="btn_Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btn_Add" runat="server" Text="Add" CommandName="Add" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_Delete" runat="server" OnClientClick="javascript:return confirm('Are you sure?');" Text="Delete" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%#Eval("LOOKUP_VALUE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<RowStyle BackColor="White" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<FooterStyle BackColor="#4DA6A6" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<HeaderStyle BackColor="#4DA6A6" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<PagerSettings Mode="Numeric" Position="Bottom" />
<SelectedRowStyle BackColor="#e3f561" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
</asp:GridView>
<asp:Label ID="lblEmpty" runat="server" Visible="false" Style="font-weight:bold; font-size:large;"></asp:Label>
</div>
</asp:Panel>
Everything works fine in terms of displaying what I need to see. In the code-behind, I have a few functions to handle everything but adding a new record:
protected void DataGrid_Leads_EditCommand(object sender, GridViewEditEventArgs e)
{
DataGrid_Leads.EditIndex = e.NewEditIndex;
LoadLeadsGrid();
}
protected void DataGrid_Leads_UpdateCommand(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(DataGrid_Leads.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)DataGrid_Leads.Rows[e.RowIndex];
Label lbl_ID = (Label)DataGrid_Leads.Rows[e.RowIndex].FindControl("lbl_ID");
TextBox txt_Name = (TextBox)DataGrid_Leads.Rows[e.RowIndex].FindControl("txt_Name");
DataGrid_Leads.EditIndex = -1;
OracleConnection conn = GetConnection();
conn.Open();
////SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
OracleCommand cmd = new OracleCommand("UPDATE MY_VALUES set LOOKUP_DESCRIPTION = '" + txt_Name.Text + "' where LOOKUP_VALUE = '" + userid + "' AND LOOKUP_AREA = 'LEAD'", conn);
cmd.ExecuteNonQuery();
conn.Close();
LoadLeadsGrid();
}
protected void DataGrid_Leads_DeleteCommand(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(DataGrid_Leads.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)DataGrid_Leads.Rows[e.RowIndex];
Label lbldeleteid = (Label)row.FindControl("lbl_ID");
OracleConnection conn = GetConnection();
conn.Open();
OracleCommand cmd = new OracleCommand("DELETE FROM MY_VALUES where LOOKUP_VALUE = '" + userid + "' AND LOOKUP_AREA = 'LEAD'", conn);
cmd.ExecuteNonQuery();
conn.Close();
LoadLeadsGrid();
}
protected void DataGrid_Leads_CancelCommand(object sender, GridViewCancelEditEventArgs e)
{
DataGrid_Leads.EditIndex = -1;
LoadLeadsGrid();
}
So, how do I handle that "Add" button? I read online that you would use a RowCommand function, but when I added one and put a break point inside it, the code never entered that function.
Any help is appreciated.
try something like this
void ProductsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Add")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ProductsGridView.Rows[index];
// Create a new ListItem object for the product in the row.
ListItem item = new ListItem();
item.Text = Server.HtmlDecode(row.Cells[1].Text);
// If the product is not already in the ListBox, add the ListItem
// object to the Items collection of the ListBox control.
if (!ProductsListBox.Items.Contains(item))
{
ProductsListBox.Items.Add(item);
}
}
}
<asp:GridView ID="ProductsGridView"
DataSourceID="ProductsDataSource"
AllowPaging="true"
AutoGenerateColumns="false"
OnRowCommand="ProductsGridView_RowCommand"
OnRowCreated="ProductsGridView_RowCreated"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server"
ID="AddButton"
CommandName="Add"
Text="Add" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name"
HeaderText="Product Name"/>
<asp:BoundField DataField="ProductNumber"
HeaderText="Product Number"/>
</Columns>
</asp:GridView>
you dont need gridview command. you can add command to directly add button..
<asp:Button ID="btn_Add" runat="server" Text="Add" CommandName="Add" />
change to
<asp:Button ID="btn_Add" runat="server" Text="Add" OnClick="btn_Add_Click" />
server side :
protected void btn_Add_Click(object sender, EventArgs e)
{
var textBox = GridView1.FooterRow.FindControl("ntxt_Name") as TextBox;
if (textBox != null)
{
var value = textBox.Text;
// insert operation
}
}
I have a large dataset binding to a gridview that is inside of a 300px height restricted DIV tag. When I select a row and trigger the edit function the page reloads the data (as desired) into the gridview and takes me back to the top regardless of how far I may have scrolled down.
Is there a way ideally only using asp.net c# to focus on the row that is being edited. I don't mind if this involves the row being placed at the top of the grid while in edit mode if that is required.
Below is CountryGrid.aspx
<%# Page Language="C#" MasterPageFile="~/MasterPageSimple.master" AutoEventWireup="true"
CodeFile="CountryGrid.aspx.cs" EnableEventValidation="false" Inherits="CountryGrid"
Title="JFA Admin Portal - OP49 Country Update" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<center>
<div class="headlanding">
<asp:Label ID="lb_Welcome" runat="server" CssClass="labelLargeFont" Text="Label">OP49 - Country Update</asp:Label>
<br />
<br />
<br />
<asp:Label ID="Label4" runat="server" CssClass="labelLargeFont" >You are currently modifying: </asp:Label>
<asp:Label ID="Country" runat="server" CssClass="labelLargeFont" />
<br />
<asp:Label ID="Label1" runat="server" CssClass="labelLargeFont" >For </asp:Label>
<asp:Label ID="Season" runat="server" CssClass="labelLargeFont" />
<br />
<br />
</div>
<br />
<div style="text-align: center">
<asp:Label ID="Error_Dashboard" runat="server" Font-Size="Small" ForeColor="#FF3300"></asp:Label>
<asp:Label ID="ErrorAccess" runat="server" Font-Size="Small" ForeColor="#FF3300"></asp:Label>
</center>
</div>
<asp:Panel ID="Panel1" runat="server" Font-Size="Large" CssClass="Grid_Panel" GroupingText="OP49 - Update Grid" Font-Bold="true">
<center>
<div style="max-height: 550px; overflow: auto;">
<asp:GridView ID="CountryGridView" DataKeyNames="i_SK_Accom" runat="server" Postback="False"
AutoGenerateColumns="False" CssClass="mGrid" RowStyle-CssClass="normal" Width="95%"
OnRowEditing="CountryGridView_RowEditing"
OnRowCancelingEdit="CountryGridView_RowCancelingEdit"
OnRowUpdating="CountryGridView_RowUpdating" >
<Columns>
<asp:TemplateField HeaderText="Accom Code">
<ItemTemplate>
<asp:Label ID="lb_Accom_Code" runat="server" Text='<%# Bind("Accom_Code") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lbl_Accom_Code" runat="server" Text='<%# Bind("Accom_Code") %>' />
</EditItemTemplate>
<HeaderStyle Width="80px" />
<ItemStyle Width="80px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Accom Name">
<ItemTemplate>
<asp:Label ID="lb_Accom_Name" runat="server" Text='<%# Bind("Accom_Name") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lbl_Accom_Name" runat="server" Text='<%# Bind("Accom_Name") %>' />
</EditItemTemplate>
<HeaderStyle Width="200px" />
<ItemStyle Width="200px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="OP49 Required?">
<EditItemTemplate>
<asp:DropDownList ID="txt_OP49" runat="server" SelectedValue='<%# Bind("OP49_Required") %>' CssClass="DropBoxYN">
<asp:ListItem Text="Yes" Value="Y"></asp:ListItem>
<asp:ListItem Text="No" Value="N"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lb_OP49" runat="server" Text='<%# Bind("OP49_Required") %>' />
</ItemTemplate>
<HeaderStyle Width="100px" />
<ItemStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Weekly">
<EditItemTemplate>
<asp:DropDownList ID="txt_Weekly" runat="server" SelectedValue='<%# Bind("Weekly") %>' CssClass="DropBoxYN">
<asp:ListItem Text="Yes" Value="Y"></asp:ListItem>
<asp:ListItem Text="No" Value="N"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lb_Weekly" runat="server" Text='<%# Bind("Weekly") %>' />
</ItemTemplate>
<HeaderStyle Width="60px" />
<ItemStyle Width="60px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Daily">
<EditItemTemplate>
<asp:DropDownList ID="txt_Daily" runat="server" SelectedValue='<%# Bind("Daily") %>' CssClass="DropBoxYN">
<asp:ListItem Text="Yes" Value="Y"></asp:ListItem>
<asp:ListItem Text="No" Value="N"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lb_Daily" runat="server" Text='<%# Bind("Daily") %>' />
</ItemTemplate>
<HeaderStyle Width="60px" />
<ItemStyle Width="60px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions" >
<ItemTemplate>
<asp:ImageButton ID="bt_Edit" runat="server" CommandName="Edit" AlternateText="Edit" ImageUrl="~/Images/Edit.gif" CssClass="ImageButton" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="bt_Update" runat="server" CommandName="Update" AlternateText="Update" ImageUrl="~/Images/save.png" CssClass="ImageButton" />
<asp:ImageButton ID="bt_Cancel" runat="server" CommandName="Cancel" AlternateText="Cancel" ImageUrl="~/Images/cancel.png" CssClass="ImageButton" />
</EditItemTemplate>
<HeaderStyle Width="60px" />
<ItemStyle Width="60px" Wrap="False" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<br />
<asp:ImageButton ID="Home" runat="server" ImageUrl="~/Images/home.png" CssClass="ImageButtonLarge" AlternateText="Home" ToolTip="Home" OnClick="Click_Home" />
</center>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
And the code behind page:
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;
using System.Text;
public partial class CountryGrid : System.Web.UI.Page
{
SnowballInterface conn = new SnowballInterface();
SnowballInterface CurSeason = new SnowballInterface();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
if (Request["i_FK_CountryID"] == null)
{
Response.Redirect("Default.aspx");
}
#region Get Accom Data
SqlCommand EditCOComm = new SqlCommand("IFACE_JFA_COUNTRY", conn.sbConn);
EditCOComm.CommandType = CommandType.StoredProcedure;
EditCOComm.Parameters.Add("#Statement", SqlDbType.Char).Value = "CountryDetails";
EditCOComm.Parameters.Add("#i_FK_CountryID", SqlDbType.Int).Value = Request["i_FK_CountryID"].Trim().ToString();
try
{
conn.sbConn.Open();
SqlDataReader EditCOReader;
EditCOReader = EditCOComm.ExecuteReader();
// Download default values
while (EditCOReader.Read())
{
Country.Text = Convert.ToString(EditCOReader["Country_Name"]).Trim();
Season.Text = Convert.ToString(EditCOReader["Season_Name"]).Trim();
}
EditCOReader.Close();
}
catch (Exception)
{
}
finally
{
conn.sbConn.Close();
}
#endregion
if (!IsPostBack)
{
BindCountryGrid();
}
}
protected void CountryGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
CountryGridView.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindCountryGrid();
}
protected void CountryGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
CountryGridView.EditIndex = -1;
//Bind data to the GridView control.
BindCountryGrid();
}
protected void CountryGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label Textbox_Accom = (Label)CountryGridView.Rows[e.RowIndex].FindControl("lbl_Accom_Code");
Label Textbox_Accom_Name = (Label)CountryGridView.Rows[e.RowIndex].FindControl("lbl_Accom_Name");
DropDownList Textbox_OP49 = (DropDownList)CountryGridView.Rows[e.RowIndex].FindControl("txt_OP49");
DropDownList Textbox_Weekly = (DropDownList)CountryGridView.Rows[e.RowIndex].FindControl("txt_Weekly");
DropDownList Textbox_Daily = (DropDownList)CountryGridView.Rows[e.RowIndex].FindControl("txt_Daily");
SqlCommand commEditConsultant = new SqlCommand("IFACE_JFA_ACCOM", conn.sbConn);
commEditConsultant.CommandType = CommandType.StoredProcedure;
commEditConsultant.Parameters.Add("#Statement", SqlDbType.VarChar).Value = "AccomGridUpdate";
commEditConsultant.Parameters.Add("#Page", SqlDbType.VarChar).Value = "OP49";
commEditConsultant.Parameters.Add("#PC_Username", SqlDbType.VarChar).Value = HttpContext.Current.User.Identity.Name.ToUpper().ToString();
commEditConsultant.Parameters.Add("#Season_Name", SqlDbType.VarChar).Value = Season.Text;
commEditConsultant.Parameters.Add("#Accom_Code", SqlDbType.VarChar).Value = Textbox_Accom.Text;
commEditConsultant.Parameters.Add("#i_FK_SeasonID", SqlDbType.VarChar).Value = Request["i_FK_SeasonID"].Trim().ToString();
commEditConsultant.Parameters.Add("#OP49_Required", SqlDbType.VarChar).Value = Textbox_OP49.Text;
commEditConsultant.Parameters.Add("#Weekly", SqlDbType.VarChar).Value = Textbox_Weekly.Text;
commEditConsultant.Parameters.Add("#Daily", SqlDbType.VarChar).Value = Textbox_Daily.Text;
conn.sbConn.Open();
commEditConsultant.ExecuteNonQuery();
CountryGridView.EditIndex = -1;
Error_Dashboard.Text = Textbox_Accom.Text + " - " + Textbox_Accom_Name.Text + " Updated Successfully!";
conn.sbConn.Close();
BindCountryGrid();
}
private void BindCountryGrid()
{
SqlCommand CountryGridSelect = new SqlCommand("IFACE_JFA_ACCOM", conn.sbConn);
CountryGridSelect.CommandType = CommandType.StoredProcedure;
CountryGridSelect.Parameters.Add("#Statement", SqlDbType.VarChar).Value = "CountryGridSelect";
CountryGridSelect.Parameters.Add("#i_FK_CountryID", SqlDbType.VarChar).Value = Request["i_FK_CountryID"].Trim().ToString();
try
{
conn.sbConn.Open();
SqlDataReader CountryGridSelectReader;
CountryGridSelectReader = CountryGridSelect.ExecuteReader();
CountryGridView.DataSource = CountryGridSelectReader;
CountryGridView.DataBind();
CountryGridSelectReader.Close();
}
finally
{
conn.sbConn.Close();
}
}
protected void Click_Home(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?i_FK_SeasonID=" + Request["i_FK_SeasonID"].Trim().ToString());
}
}
You can set MaintanScrollPositionOnPostback to true in page directives on your aspx page.
<%# Page Language="C#" AutoEventWireup="true" MaintainScrollPositionOnPostback="true" CodeBehind="Gridview.aspx.cs" Inherits="TestWebsite.Gridview" %>
I have a GridView in my page :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" BackColor="White"
AutoGenerateColumns="False" EmptyDataText="No data available." BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4" Width="729px" ForeColor="Black"
GridLines="Vertical" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<RowStyle BackColor="#F7F7DE" />
<Columns>
<asp:TemplateField HeaderText="TransactionKey" SortExpression="TransactionKey">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewTransactionKey" runat="server" Text='<%# Bind("TextBoxTransactionKey") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewTransactionKey" runat="server" Text='<%# Bind("TextBoxTransactionKey") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="TerminalID" SortExpression="TerminalID">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewTerminalID" runat="server" Text='<%# Bind("TextBoxTerminalID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewTerminalID" runat="server" Text='<%# Bind("TextBoxTerminalID") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="MerchantID" SortExpression="MerchantID">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewMerchantID" runat="server" Text='<%# Bind("TextBoxMerchantID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewMerchantID" runat="server" Text='<%# Bind("TextBoxMerchantID") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="شماره حساب" SortExpression="شماره حساب">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewBankAccount" runat="server" Text='<%# Bind("TextBoxBankAccount") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewBankAccount" runat="server" Text='<%# Bind("TextBoxBankAccount") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="نام بانک" SortExpression="نام بانک">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" >
<ItemStyle Font-Size="12px" />
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
I set the DataSource with the follwing code :
protected void Page_Load(object sender, EventArgs e)
{
try
{
LabelTitr.Text = "Add Banks";
LabelResult.Text = "";
if (Session["Username"] != null)
{
string permission = "";
bool login = PublicMethods.CheckUsernamePass(Session["Username"].ToString(), Session["Password"].ToString(), out permission);
if (!login)
{
permission = "";
Response.Redirect("../Default.aspx");
Session["Username"] = Session["Password"] = null;
return;
}
}
else
{
Response.Redirect("../Default.aspx");
Session["Username"] = Session["Password"] = null;
return;
}
if (!IsPostBack)
BindDataToGridView1();
}
catch (Exception ex)
{
LabelResult.Text = ex.Message;
}
}
void BindDataToGridView1()
{
try
{
DataSet1 dataSet = new DataSet1();
DataClasses2DataContext dbc2 = new DataClasses2DataContext();
var Definitions = dbc2.Definitions;
if (Definitions.Count() <= 0) return;
foreach (var Definition in Definitions)
{
string bankName = dbc2.Banks.Where(c => c.BankID == Definition.BankID).First().BankName;
string CheckBox = "<input name=\"CheckBoxSubmitChanges\" type=\"checkbox\" value=" + Definition.DefinitionID + " />";
dataSet.DataTableBanks.Rows.Add(bankName, Definition.BankAccount, Definition.MerchantID, Definition.TerminalID, Definition.TerminalID);
GridView1.DataSource = dataSet.DataTableBanks;
}
GridView1.DataBind();
}
catch (Exception ex)
{
LabelResult.Text = ex.Message;
}
}
and this is GridView1_SelectedIndexChanged method :
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string temp = row.Cells[4].Text;
LabelResult.Text = temp;
}
But always temp string is empty !!!
What's wrong with it ?
Thanks
If it's a TemplateField, you have to use the FindControl("control ID") option, not the text fo the cell. I count cell 4 as being a templatefield...
There is no Text as your data is stored in controls. You need to search for the control you want and pull the Text out of.
Eg:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string temp = row.Cells[4].FindControl('LabelGridViewBankName').Text;
LabelResult.Text = temp;
}
Optionally you could could key off the DataKey property if you are using it and then use it to search your datasource for the value you want.
//this will give you control over the textbox object
var field = (TextBox)(GridView1.Rows[e.RowIndex].FindControl("your_control_ID"));
//and here you can access the text
string temp = field.Text;
I'm trying to give the user the ability to create a new record from the footer row and my event handler doesn't seem to be working... or maybe I'm going at this all wrong.
The insert button that I enabled in the gridview doesn't work either...checkout the site at http://aisched.engr.oregonstate.edu/admin/courses.aspx
Here is my code in front and behind:
public partial class admin_courses : System.Web.UI.Page
{
public Table table;
ListDictionary listValues = new ListDictionary();
TextBox textBox1 = new TextBox(); //Name
TextBox textBox2 = new TextBox(); //CR
TextBox textBox3 = new TextBox(); //CourseNum
TextBox textBox4 = new TextBox(); //Dept
protected void Page_Init()
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Footer) return; //Escape if not footer
textBox1.ID = "name";
textBox1.Width = 250;
textBox2.ID = "credit_hours";
textBox2.Width = 25;
textBox3.ID = "dept";
textBox3.Width = 30;
textBox4.ID = "class";
textBox4.Width = 25;
LinkButton add = new LinkButton();
add.ID = "add";
add.Text = "Add course";
add.CommandName = "add";
add.Click += new EventHandler(add_Click);
e.Row.Cells[1].Controls.Add(textBox1);
e.Row.Cells[2].Controls.Add(textBox2);
e.Row.Cells[3].Controls.Add(textBox3);
e.Row.Cells[4].Controls.Add(textBox4);
e.Row.Cells[5].Controls.Add(add);
}
public void add_Click(object sender, EventArgs e)
{
Response.Write("you Clicked Add Course!");
if (textBox1.Text != null && textBox2.Text != null && textBox3.Text != null && textBox4.Text != null) {
listValues.Add("name", textBox1.Text);
listValues.Add("credit_hours", textBox2.Text);
listValues.Add("dept", textBox4.Text); //For Visual
listValues.Add("class", textBox3.Text);
}
LinqDataSource1.Insert(listValues);
Response.Redirect("~/admin/courses.aspx");
}
}
<%# Page Language="C#" MasterPageFile="~/admin.master" AutoEventWireup="true" CodeFile="courses.aspx.cs" Inherits="admin_courses" Title="OSU Aisched | Admin - Courses" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="admin_nav_links" Runat="Server">
<ul id="main">
<li>Overview</li>
<li>Users</li>
<li class="current_page_item">Courses</li>
<li>Programs</li>
<li>Sections</li>
<li>Import</li>
<li>Logs</li>
</ul>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataClassesDataContext" EnableDelete="True"
EnableInsert="True" EnableUpdate="True" TableName="courses">
</asp:LinqDataSource>
<h1><a>Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="course_id" DataSourceID="LinqDataSource1"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2" AllowSorting="True" ShowFooter="True"
OnRowDataBound="GridView1_RowDataBound" >
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:BoundField DataField="course_id" HeaderText="ID"
ReadOnly="True" SortExpression="course_id" />
<asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
<asp:BoundField DataField="credit_hours" HeaderText="CR"
SortExpression="credit_hours" />
<asp:BoundField DataField="dept" HeaderText="Dept" SortExpression="dept" />
<asp:BoundField DataField="class" HeaderText="#" SortExpression="class" />
<asp:CommandField DeleteImageUrl="~/media/delete.png" ShowDeleteButton="True"
ShowEditButton="True" ShowInsertButton="True"/>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<br />
<asp:HyperLink ID="HyperLink1" runat="server" Target="~/admin/addCourse.aspx" Enabled="true"NavigateUrl="~/admin/addCourse.aspx" Text="Add New course"></asp:HyperLink>
<br />
</form>
</asp:Content>
I expect (or at least I certainly hope) there's a better way to do this, but try this:
<asp:LinqDataSource runat="server" ID="LinqDataSource1" ContextTypeName="Courses.DataClassesDataContext" TableName="Courses" EnableDelete="True" EnableUpdate="True" EnableInsert="True" />
<h1>
<a>
Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="course_id"
DataSourceID="LinqDataSource1" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"
BorderWidth="1px" CellPadding="3" CellSpacing="2" AllowSorting="True"
ShowFooter="True">
<Columns>
<asp:BoundField DataField="course_id" HeaderText="course_id" ReadOnly="True" SortExpression="course_id"
InsertVisible="False" />
<asp:TemplateField HeaderText="name" SortExpression="name" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NameTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="credit_hours" SortExpression="credit_hours">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="HoursTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dept" SortExpression="dept">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("dept") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("dept") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="DeptTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="class" SortExpression="class">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("class") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("class") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ClassTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</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>
<FooterTemplate>
<asp:LinkButton ID="AddLinkButton" runat="server" CommandName="Add" Text="Add" CausesValidation="true" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
// We are in a Postback so check to see if the AddLinkButton was clicked
String eventTarget = Request.Form["__EVENTTARGET"].ToString();
if (eventTarget.EndsWith("addlinkbutton",StringComparison.InvariantCultureIgnoreCase))
{
// We are adding a new row so build a ListDictionary with the controls from the footer row
ListDictionary values = new ListDictionary();
values.Add("name", ((TextBox)GridView1.FooterRow.FindControl("NameTextBox")).Text);
values.Add("credit_hours", ((TextBox)GridView1.FooterRow.FindControl("HoursTextBox")).Text);
values.Add("dept", ((TextBox)GridView1.FooterRow.FindControl("DeptTextBox")).Text);
values.Add("class", ((TextBox)GridView1.FooterRow.FindControl("ClassTextBox")).Text);
// Pass the ListDictionary to the data source to send off to the database
LinqDataSource1.Insert(values);
// Refresh the grid so it shows the row we just added
GridView1.DataBind();
}
}
}
catch (Exception)
{
throw;
}
}
I couldn't make it work without writing code manually to do the Insert. Handling the AddLinkButton_Click event in the Page_Load event by examining the EventTarget hidden field to see if it ends with 'addlinkbutton' feels quite wrong, but it works.
A Sample pseudo code which can add from grid view footer, Initially data's are saved under View State, Using button click event to check the ViewState and insert the new data to the table.
aspx code
<asp:GridView ID="gvUser" runat="server" AutoGenerateColumns="false" ShowFooter="true" OnRowDataBound="gvUser_RowDataBound"
OnRowCommand="gvUser_RowCommand" OnRowDeleting="gvUser_RowDeleting" OnRowEditing="gvUser_RowEditing" CssClass="table table-bordered table-hover table-striped">
<EmptyDataTemplate>
No Data Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="User Details" HeaderStyle-Width="25%">
<ItemTemplate>
<asp:Label ID="lblCourse" runat="server" Text='<%# Eval("Details") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDetails" runat="server" DataTextField="Name" DataValueField="ID" CssClass="form-control" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="user Check One" HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckOne" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckOne").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckOne" runat="server" CssClass="i-checks" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HR Rec." HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckTwo" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckTwo").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckTwo" runat="server" CssClass="i-checks" />
</FooterTemplate>
<ItemStyle Wrap="true" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" CausesValidation="false" CommandName="Edit" ImageUrl="~/Contents/Images/pencil.svg" Width="20" Height="20"
ToolTip="Edit"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" CausesValidation="false" CommandName="Delete" ImageUrl="~/Contents/Images/remove.svg" Width="20" Height="20"
ToolTip="Delete"></asp:ImageButton>
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgBtnAdd" runat="server" CausesValidation="true" CommandName="Add" ImageUrl="~/Contents/Images/add.svg" Width="20" Height="20"
ToolTip="Add"></asp:ImageButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Server side code
protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
List<TableOne> controlDetails = new List<TableOne>();
controlDetails = dc.TableOne.Where(condition).ToList();
controlDetails.Insert(0, new TableOne() { ID = 0, Name = "Select Details" });
DropDownList ddlDetails = (e.Row.FindControl(ddlDetails) as DropDownList);
ddlDetails.DataSource = controlDetails;
ddlDetails.DataTextField = "Name";
ddlDetails.DataValueField = "ID";
ddlDetails.DataBind();
}
}
protected void gvUser_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
dr.Delete();
gvUser.Rows[RowIndex].Visible = false;
}
else if (e.CommandName == "Edit")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
ddlDetails.SelectedValue = dr["DetailID"].ToString();
CheckOne.Checked = Convert.ToBoolean(dr["CheckOne"]);
CheckTwo.Checked = Convert.ToBoolean(dr["CheckTwo"]);
dr.Delete();
}
else if (e.CommandName == "Add")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
if (ViewState["gvUser"] != null)
{
DataTable existingTable = (DataTable)ViewState["gvUser"];
existingTable.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = existingTable;
gvUser.DataSource = existingTable;
gvUser.DataBind();
}
else
{
DataTable dtUsers = new DataTable();
dtUsers.Columns.Add("ID");
dtUsers.Columns.Add("UserID");
dtUsers.Columns.Add("DetailsID");
dtUsers.Columns.Add("Details");
dtUsers.Columns.Add("CheckOne");
dtUsers.Columns.Add("CheckTwo");
dtUsers.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = dtUsers;
gvUser.DataSource = dtUsers;
gvUser.DataBind();
}
}
}
catch (Exception)
{
}
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (ViewState["gvUser"] != null)
{
TableOne userInfo = null;
List<TableOne> userDetails = new List<TableOne>();
DataTable userSpecificDetails = (DataTable)ViewState["gvUser"];
for (int i = 0; i < userSpecificDetails.Rows.Count; i++)
{
userInfo = new TableOne();
userInfo.UserID = UserID; //supply value
foreach (DataColumn col in userSpecificDetails.Columns)
{
switch (col.ColumnName)
{
case "DetailsID":
userInfo.DetailsID = Convert.ToInt16(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckOne":
userInfo.CheckOne = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckTwo":
userInfo.CheckTwo = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
}
}
userDetails.Add(userInfo);
}
if (userDetails.Count > 0)
{
dc.TableOne.InsertAllOnSubmit(userDetails);
dc.SubmitChanges();
}
}
}