I have four text-boxes, two buttons one grid-view and one check-box and i put require field validation on each text-box i have a database so that when i enter value in the text-boxes and press submit button data store in the database and show in gird as i use datatable. i Have edit, delete and update link in my grid-view now when i click on edit or delete link validation error message displayed and i won't make changes in my grid. can any one help me on this.
Thanks in advance
My aspx code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="height: 191px">
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td class="style3">
FirstName</td>
<td>
<asp:TextBox ID="tFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="tFirstName" ErrorMessage="Enter First Name">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style3">
Last name</td>
<td>
<asp:TextBox ID="tLastName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="tLastName" ErrorMessage="Enter Last Name">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style3">
Age</td>
<td>
<asp:TextBox ID="tAge" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="tAge" ErrorMessage="" dalega">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style7">
Is Active</td>
<td class="style8">
<asp:CheckBox ID="dropActive" runat="server" />
</td>
</tr>
<tr>
<td class="style3">
Auto ID</td>
<td>
<asp:TextBox ID="autoID" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="autoID" ErrorMessage="Marzi hai teri">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style6">
</td>
<td class="style5">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Sumit" ValidationGroup="abc"/>
<input type="reset" />
<br />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" Height="72px" />
</td>
</tr>
<tr>
<td class="style4" colspan="2">
<asp:Label ID="lblMessage" runat="server" ForeColor="Green" EnableViewState="false" />
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="false" Width="36%" OnRowEditing="EditRow" OnRowCancelingEdit="CancelEditRow" OnRowUpdating="UpdateRow" DataKeyNames="AutoId" OnRowDeleting="DeleteRow" AllowPaging="true" OnPageIndexChanging="ChangePage" AllowSorting="True">
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" />
<asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="AutoId" DataField="AutoId" ReadOnly="true" />
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<%# Eval("FirstNAme") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<%# Eval("LastName") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<%# Eval("Age") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>' Columns="3" />
<asp:RequiredFieldValidator ID="REw" runat="server" ControlToValidate="txtAge" Text="*" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<EditItemTemplate>
<asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active") %>'>
<asp:ListItem Text="Yes" Value="True" />
<asp:ListItem Text="No" Value="False" />
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to delete?')">
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#efefef" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</table>
</div>
</form>
</body>
</html>
code for aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateData();
}
}
protected void EditRow(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.PopulateData();
}
protected void CancelEditRow(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
this.PopulateData();
}
protected void DeleteRow(object sender, GridViewDeleteEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=EMS;Integrated Security=True"))
{
string sql = "Delete from PersonalDetail" +" where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text ="Record has been deleted successfully !";
lblMessage.ForeColor = System.Drawing.
Color.Red;
this.PopulateData();
}
protected void ChangePage(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.PopulateData();
}
protected void UpdateRow(object sendedr, GridViewUpdateEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
TextBox tFirstName = row.FindControl("txtFirstName") as TextBox;
TextBox tLastName = row.FindControl("txtLastName") as TextBox;
TextBox tAge = row.FindControl("txtAge") as TextBox;
DropDownList dropActive = row.FindControl("dropActive") as DropDownList;
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=EMS;Integrated Security=True"))
{
string sql = "Update PersonalDetail set FirstName = #FirstName,LastName=#LastName, Age= #Age, Active = #Active" + " where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#FirstName", tFirstName.Text.Trim());
cmd.Parameters.AddWithValue("#LastName", tLastName.Text.Trim());
cmd.Parameters.AddWithValue("#Age", tAge.Text.Trim());
cmd.Parameters.AddWithValue("#Active", dropActive.SelectedValue);
cmd.Parameters.AddWithValue("#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text ="Record updated successfully !";
GridView1.EditIndex = -1;
this.PopulateData();
}
private void PopulateData()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=EMS;Integrated Security=True"))
{
string sql = "Select * from PersonalDetail";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=EMS;Integrated Security=True");
con.Open();
string FirstName = tFirstName.Text;
string LastName = tLastName.Text;
string Age = tAge.Text;
string Active = dropActive.Text;
string AutoId = autoID.Text;
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "insert into PersonalDetail(FirstName,LastName,Age,Active,AutoId) values('" + FirstName + "','" + LastName + "','" + Age + "','" + Active + "','" + AutoId + "')";
cmd.Parameters.AddWithValue("#FirstName", tFirstName.Text.Trim());
cmd.Parameters.AddWithValue("#LastName", tLastName.Text.Trim());
cmd.Parameters.AddWithValue("#Age", tAge.Text.Trim());
cmd.Parameters.AddWithValue("#Active", dropActive.Text.Trim());
cmd.Parameters.AddWithValue("#AutoId", autoID.Text.Trim());
cmd.ExecuteNonQuery();
}
con.Close();
tFirstName.Text = string.Empty;
tLastName.Text = string.Empty;
tAge.Text = string.Empty;
dropActive.Text = string.Empty;
tFirstName.Focus();
}
None of your Validation control has a Validation Group.
Add this to all your RequiredFieldValidator.
ValidationGroup="SomeName"
Make sure all your RequiredFieldValidator has the same ValidationGroup
Now finally add the ValidationGroup="SomeName" to your Button control which when clicked raises the Validation controls.
I just use this.populate(); on button1 to show grid-view after enter details in the text-boxes thanks for your reply guys.
Try removing validation checking from your link CauseValidation="false"
<ItemTemplate>
<asp:LinkButton CauseValidation="false" ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
Related
I have the following asp:GridView
<asp:GridView ID="contacts" runat="server" AutoGenerateColumns="false" Width="100%">
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:HiddenField ID="ContactID" runat="server" Value='<%# Bind("employerdetailcontactid") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Action" ItemStyle-CssClass="center" >
<ItemTemplate>
<asp:Label ID="ActionLabel" runat="server" Text='<%# Bind("action") %>' />
<asp:CheckBox ID="Action" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="First Name">
<ItemTemplate>
<asp:TextBox ID="FirstName" runat="server" Text='<%# Bind("firstname") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Last Name">
<ItemTemplate>
<asp:TextBox ID="LastName" runat="server" Text='<%# Bind("lastname") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="E-Mail">
<ItemTemplate>
<asp:TextBox ID="Email" runat="server" Text='<%# Bind("email") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Phone Number">
<ItemTemplate>
<asp:TextBox ID="PhoneNumber" runat="server" Text='<%# Bind("phonenumber") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Send E-mail" ItemStyle-CssClass="center" >
<ItemTemplate>
<asp:CheckBox ID="SendEmail" runat="server" Checked='<%# Convert.ToBoolean( Eval("sendemail")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The GridView has however many rows from the database, plus one extra row for adding a new row. Very rarely will the end-user ever add more than one contact at a time, so I am not going to bother having an "Add Row" button. I want the rows from the database to have the label say "Delete" and the manually added row have the label say "New". Here is my code to populate the GridView:
SqlCommand cmd = new SqlCommand("SELECT *,'Delete' as action FROM contact WHERE employerid=#employerid", conn);
cmd.Parameters.AddWithValue("#employerid", id);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
//These are added to be able to manually add a row below
dt.Columns.Add("ContactID");
dt.Columns.Add("Action");
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("Email");
dt.Columns.Add("PhoneNumber");
dt.Columns.Add("SendEmail");
dt.Load(dr);
DataRow drow = dt.NewRow();
drow["ContactID"] = 0;
drow["Action"] = false;
drow["FirstName"] = "";
drow["LastName"] = "";
drow["Email"] = "";
drow["PhoneNumber"] = "";
drow["SendEmail"] = "False";
dt.Rows.Add(drow);
contacts.DataSource = dt;
contacts.DataBind();
How would I set the text of ActionLabel to "New" for the manually added row ?
You have two options:
Attach for the RowDataBound event and programmatically set the text
<asp:TemplateField HeaderText ="Action" ItemStyle-CssClass="center" >
<ItemTemplate>
<asp:Label ID="ActionLabel" runat="server" Text='<%# Bind("action") %>' />
<asp:CheckBox ID="Action" runat="server" />
</ItemTemplate>
</asp:TemplateField>
//use the onItemDatabound
void contacts_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// get contact id to identify whether this is fake row
int contactId = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ContactID"));
string labelText = contactId > 0 ? "Delete" : "New";
((Label)e.Item.FindControl("ActionLabel")).Text = labelText;
}
}
Option 2: Use FooterRow template and enable footer row in the GridView component
<asp:GridView ShowFooter = "true"
...
<asp:TemplateField HeaderText ="Action" ItemStyle-CssClass="center" >
<ItemTemplate>
<asp:Label ID="ActionLabel" runat="server" Text="Delete" />
<asp:CheckBox ID="Action" runat="server" />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="ActionLabel" runat="server" Text="New" />
<asp:CheckBox ID="Action" runat="server" />
</FooterTemplate>
</asp:TemplateField>
I am a little confused whether I modified the right GridView column, but I think you'll get the idea
I have two dropdownlists that are used to generate a gridview that will be edited and updated. I am lost as to why the gridview will not populate. I am enclosing the coded that I have. I have tried hiddenfields, I have parameters right now that seem to be populating correctly, I am just very confused as to why I can't see the gridview. As a caveat, I need to be able to update the certain columns in the rows either by text box or dropdownlist. If I change the query on the datasource for the gridview to bring in every row I have in the database, I can see everything and edit and update perfectly.
Here is the code first my aspx then the aspx.cs
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Annos3.aspx.cs" Inherits="SHCAnnotation.WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="dlJobName" runat="server" AutoPostBack="True"
DataSourceID="JobName" DataTextField="Name" DataValueField="Name"
style="z-index: 1; left: 25px; top: 50px; position: absolute; bottom: 257px; height: 45px; width: 242px;"
onselectedindexchanged="dlJobName_SelectedIndexChanged" >
</asp:DropDownList>
<asp:SqlDataSource ID="JobName" runat="server"
ConnectionString="<%$ ConnectionStrings:SRM_MetricConnectionString %>"
SelectCommand="SELECT DISTINCT Name FROM vw_GridviewSource WHERE (DueDt > sysdatetime()) ORDER BY Name">
</asp:SqlDataSource>
<asp:GridView ID="gvSummary" runat="server" AutoGenerateColumns = "False" AllowSorting = "true"
OnRowCancelingEdit = "CancelEdit" OnRowEditing = "EditSummary" OnRowDataBound = "RowDataBound"
OnRowUpdating = "UpdateSummary" CellPadding="4" ForeColor="#333333"
GridLines="None" DataKeyNames="AnnotationNumber, Cust, Name, AnnotationDate"
style="z-index: 1; left: 10px; top: 130px; position: absolute; height: 133px; width: 257px" >
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<columns>
<asp:CommandField ShowEditButton="true" />
<asp:TemplateField HeaderText = "Annotation Number">
<ItemTemplate>
<asp:Label ID = "lblAnno" runat="server" Text='<%# Eval("AnnotationNumber") %>'> </asp:Label>
</ItemTemplate>
<HeaderStyle Width="300px" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Annotation By" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblAnnoBy" runat="server" Text='<%# Eval("AnnotationBy") %>' Width = "150"> </asp:Label>
</ItemTemplate>
<HeaderStyle Width="450" />
<ItemStyle Width="450" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Annotation Type">
<ItemTemplate>
<asp:Label ID = "lblAnnoType" runat="server" Text='<%# Eval("AnnotationType") %>' Width = "150"> </asp:Label>
</ItemTemplate>
<HeaderStyle Width="450px" />
<ItemStyle Width="450px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Business Unit" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblBU" runat="server" Text='<%# Eval("Unit") %>' Width = "250" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblBU" runat="server" Text='<%# Eval("Unit") %>' Visible ="false"></asp:Label>
<asp:DropDownList ID = "dlBU" runat="server" AutoPostBack = "true">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle Width="300px" HorizontalAlign="Center" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Error Type" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblET" runat="server" Text='<%# Eval("ErrorType") %>' Width = "250" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblET" runat="server" Text='<%# Eval("ErrorType") %>' Visible ="false"></asp:Label>
<asp:DropDownList ID = "dlET" runat="server" AutoPostBack = "true">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle Width="300px" HorizontalAlign="Center" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Actual Agency Error" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblAA" runat="server" Text='<%# Eval("ActualAgencyError") %>' Width = "250" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAA" runat="server" Text='<%# Eval("ActualAgencyError") %>' Visible ="false"></asp:Label>
<asp:DropDownList ID = "dlAA" runat="server" AutoPostBack = "true">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle Width="300px" HorizontalAlign="Center" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "AnnotationComments">
<ItemTemplate>
<asp:Label ID = "lblAnnoComm" runat ="server" Text = '<%# Eval("AnnotationComments") %>' Width = "400"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "sgk Comments">
<ItemTemplate>
<asp:Label ID = "lblsgkComm" runat ="server" Text = '<%# Eval("sgkComments") %>' Width = "400"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Textbox ID="tbsgkComm" runat="server" Text='<%# Eval("sgkComments") %>' TextMode = "MultiLine" Columns = "40" ></asp:Textbox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center" Width="400px" />
<ItemStyle HorizontalAlign="Justify" Width="400px" />
</asp:TemplateField>
</columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</div>
<asp:DropDownList ID="dlStage" runat="server" AutoPostBack="True"
DataSourceID="Stage" DataTextField="Annotation_Date"
DataValueField="Annotation_Date" Height="45px"
style="z-index: 1; left: 360px; top: 50px; position: absolute"
Width="240px" onselectedindexchanged="dlStage_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="Stage" runat="server"
ConnectionString="<%$ ConnectionStrings:SRM_MetricConnectionString %>"
SelectCommand="SELECT DISTINCT [AnnotationDate] AS Annotation_Date FROM [vw_GridviewSource] WHERE ([Name] = #Name)">
<SelectParameters>
<asp:ControlParameter ControlID="dlJobName" Name="Name"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:HiddenField ID = "hfJN" runat="server" />
<asp:HiddenField ID = "hfST" runat="server" />
</form>
</body>
</html>
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
namespace SHCAnnotation
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//hfJN.Value = dlJobName.SelectedIndex.ToString();
//hfST.Value = dlStage.SelectedIndex.ToString();
//this.BindDataInit();
}
}
protected void EditSummary(object sender, GridViewEditEventArgs e)
{
gvSummary.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSummary.EditIndex = -1;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvSummary.EditIndex == e.Row.RowIndex)
{
DropDownList dlBU = (DropDownList)e.Row.FindControl("dlBU");
string Cust = gvSummary.DataKeys[e.Row.RowIndex].Values["Cust"].ToString();
string BUquery = "select distinct Unit from vw_BU where Business ='" + Cust + "'";
SqlCommand BUcmd = new SqlCommand(BUquery);
dlBU.DataSource = GetData(BUcmd);
dlBU.DataTextField = "Unit";
dlBU.DataValueField = "Unit";
dlBU.DataBind();
dlBU.Items.FindByValue((e.Row.FindControl("lblBU") as Label).Text).Selected = true;
DropDownList dlET = (DropDownList)e.Row.FindControl("dlET");
string ETquery = "select distinct ErrorType from ErrorType";
SqlCommand ETcmd = new SqlCommand(ETquery);
dlET.DataSource = GetData(ETcmd);
dlET.DataTextField = "ErrorType";
dlET.DataValueField = "ErrorType";
dlET.DataBind();
dlET.Items.FindByValue((e.Row.FindControl("lblET") as Label).Text).Selected = true;
DropDownList dlAA = (DropDownList)e.Row.FindControl("dlAA");
string AAquery = "select distinct AAA from ActualAgencyError";
SqlCommand AAcmd = new SqlCommand(AAquery);
dlAA.DataSource = GetData(AAcmd);
dlAA.DataTextField = "AAA";
dlAA.DataValueField = "AAA";
dlAA.DataBind();
dlAA.Items.FindByValue((e.Row.FindControl("lblAA") as Label).Text).Selected = true;
}
}
protected void UpdateSummary(object sender, GridViewUpdateEventArgs e)
{
string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
string ET = (gvSummary.Rows[e.RowIndex].FindControl("dlET") as DropDownList).SelectedItem.Value;
string AA = (gvSummary.Rows[e.RowIndex].FindControl("dlAA") as DropDownList).SelectedItem.Value;
string AnnotationNumber = gvSummary.DataKeys[e.RowIndex].Value.ToString();
string sgkComments = (gvSummary.Rows[e.RowIndex].FindControl("tbsgkComm") as TextBox).Text;
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "update vw_GridviewSource set [BusinessUnit] = #BU, [ErrorType] = #ET, [sgkComments] = #sgk, [ActualAgencyError] = #AA where [AnnotationNumber] = #AnnoNum";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#BU", BU);
cmd.Parameters.AddWithValue("#AnnoNum", AnnotationNumber);
cmd.Parameters.AddWithValue("#ET", ET);
cmd.Parameters.AddWithValue("#AA", AA);
cmd.Parameters.AddWithValue("#sgk", sgkComments);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
private void BindDataInit()
{
SqlCommand cmd = new SqlCommand();
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.Connection = con;
cmd.CommandText = "select [AnnotationNumber],[AnnotationBy],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust,Name,AnnotationDate from vw_GridviewSource" ;
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
private void BindData()
{
string selectedName = dlJobName.SelectedValue;
string selectedStage = dlStage.SelectedValue;
//SqlCommand cmd = new SqlCommand(query);
SqlCommand cmd = new SqlCommand();
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.Connection = con;
cmd.CommandText = "select [AnnotationNumber],[AnnotationBy],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust,Name,AnnotationDate from vw_GridviewSource where Name = #p1 and AnnotationDate = #p2";
//cmd.Parameters.AddWithValue("#p1",selectedName);
//cmd.Parameters.AddWithValue("#p2",selectedStage);
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string selectedName = dlJobName.SelectedValue;
string selectedStage = dlStage.SelectedValue;
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#p1",selectedName);
cmd.Parameters.AddWithValue("#p2",selectedStage);
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
protected void dlJobName_SelectedIndexChanged(object sender, EventArgs e)
{
//string JobName = Application["gJob"].ToString();
BindData();
}
protected void dlStage_SelectedIndexChanged(object sender, EventArgs e)
{
//string stage = Application["gStage"].ToString();
BindData();
}
}
}
I have a dropdownlist and a gridview control. DropDownlist is outside the gridview.
Dropdownlist contains an option Delete.
Gridview contains checkbox so that rows can be selected.
here is the gridview code:
<asp:GridView ID="gvRefDetail" runat="server" CssClass="mGrid" AutoGenerateColumns="False"
PageSize="50" Font-Names="Segoe UI" Font-Size="10pt" Width="800" AllowPaging="true"
BackColor="White" BorderColor="Silver" EmptyDataText="No Record" BorderStyle="Double"
BorderWidth="1px" CellPadding="4">
<HeaderStyle BackColor="red" />
<RowStyle BackColor="White" ForeColor="#003399" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input id="Checkbox2" type="checkbox" onclick="CheckAll(this)" runat="server" /></HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NameofReferred">
<ItemStyle Wrap="true" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lbltext" runat="server" Text='<%#Bind("NameofReferred") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txttext" runat="server" Text='<%#Bind("NameofReferred")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CustomerName">
<ItemStyle Wrap="true" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lbltext" runat="server" Text='<%#Bind("CustomerName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txttext" runat="server" Text='<%#Bind("CustomerName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#006699" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="#CCFFFF" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle BackColor="White" Font-Bold="True" ForeColor="Gray" BorderColor="Gray" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle Font-Bold="True" ForeColor="White" />
</asp:GridView>
c# code:
protected void ddlaction_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlaction.SelectedValue == "1")
{
GridViewRow gvrow = gvRefDetail.SelectedRow;
int id = Convert.ToInt32(gvrow.Cells[1].Text);
string delref = "delete from tbl_Refferal where ID='" + id + "' ";
con = new SqlConnection(conString);
con.Open();
SqlCommand cmd2 = new SqlCommand(delref, con);
int temp1 = cmd2.ExecuteNonQuery();
con.Close();
BindRef();
}
}
Now, my question is when I select a one or more rows from gridview and select the delete option from dropdownlist, the selected rows must get deleted.
How can I do this?
Code On ddlaction_SelectedIndexChanged and stringVariableContainCheckboxvalues is string variable fetch from gridview checkbox selected in format ('1,3,5,6')
if (ddlaction.SelectedValue == "1")
{
string delref = "delete from tbl_Refferal where ID in (#checkboxSelectedValues)";
con = new SqlConnection(conString);
SqlCommand cmd2 = new SqlCommand(delref, con);
cmd2.Parameters.AddWithValue("#checkboxSelectedValues", stringVariableContainCheckboxvalues);
con.Open();
int temp1 = cmd2.ExecuteNonQuery();
con.Close();
BindRef();
}
Fetch Multiple Checkbox values:
foreach (GridViewRow row in gvRefDetail.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
if (cb != null && cb.Checked)
{
// fetch values in string
}
}
I am having issue when updating gridview! everything is seems to be working. but when i hit finish editing the data will not save!
but when i click edit the correct fields prompt me to enter new value but it wont save!
here is my asp
<asp:GridView ID="GridView1" runat="server" CssClass="report"
AutoGenerateColumns="False" onrowediting="GridView1_RowEditing"
DataKeyNames="TimeID" onrowupdating="GridView1_RowUpdating"
onrowcommand="GridView1_RowCommand"
onrowcancelingedit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="date" Visible="true" ReadOnly="true" HeaderText="Date" />
<asp:BoundField DataField="Description" HeaderText="Stage Description" ReadOnly="True" />
<asp:TemplateField HeaderText="Start Time">
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtStartTime" ValidationGroup="1" Width="90px" class="TimeEntry" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="txtStartTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Time">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEndTime" class="TimeEntry" ValidationGroup="1" Width="90px" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator66" ControlToValidate="txtEndTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TimeInHours" HeaderText="Time Time (Hours)" ReadOnly="True" />
<asp:CommandField ShowEditButton="true" ShowCancelButton="true"
ButtonType="Image" EditImageUrl="~/images/edit_record.jpg"
CancelImageUrl="~/images/edit_no.jpg"
UpdateImageUrl="~/images/update_record.jpg" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="lnbCopy" runat="server" AlternateText="Delete"
CommandName="DeleteRecord" CommandArgument='<%# Bind("TimeID") %>' OnClientClick="return confirm('Are you sure you want to delete this row?');" ImageUrl="~/images/delete_record.jpg" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblTimeID" runat="server" Text='<%# Eval("TimeID") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is what i have done in behind code
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {
GridView1.EditIndex = e.NewEditIndex;
loadTable();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {
GridView1.EditIndex = -1;
loadTable();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
var StartTime = row.FindControl("txtStartTime") as TextBox;
var EndTime = row.FindControl("txtEndTime") as TextBox;
var id = row.FindControl("lblTimeID") as Label;
SqlConnection conn = new SqlConnection(conStr.GetConnectionString("myServer1"));
SqlCommand comm = new SqlCommand();
comm.CommandText = "UPDATE CDSTimeSheet SET StartTime = #StartTime, EndTime = #EndTime ,timeElapsed = datediff(minute,#startTime , #EndTime), timeInSeconds = datediff(second,#startTime , #EndTime) WHERE TimeID = #id";
comm.Connection = conn;
comm.Parameters.AddWithValue("#id", id.Text);
comm.Parameters.AddWithValue("#StartTime", StartTime.Text);
comm.Parameters.AddWithValue("#EndTime", EndTime.Text);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
GridView1.EditIndex = -1;
loadTable();
}
what am i doing wrong?
It sounds a lot like you are not calling DataBind on your grid after updating the underlying data. After you perform the update (possibly within the loadTable method that I see referenced up there), call
GridView1.DataBind();
That should refresh the data in the grid.
After your comments, I see that you're not using the NewValues collection in the GridViewUpdateEventArgs parameter to get the actual incoming, updated field values. Try this:
String StartTime = e.NewValues["StartTime"].ToString();
String EndTime = e.NewValues["EndTime"].ToString();
String id = e.Keys[0].ToString();
Note that these variables are strings now, not TextBoxs, so you don't need to add ".Text" on them when you add them as parameters.
Handle the postback, basically if you fill the grid view in each postback you are re filling the gridview with old data, that's why you retrieve data with no changes (remember after Update button this trigger a postback). So, in case this is your case, try this.
if(!this.IsPostback)
{
(Method that fills your GridView)
}
Is it possible to get a FormView to automatically default to ReadOnly mode on the record that it has just inserted via its InsertItemTemplate? It seems like this would be somethign that should come naturally to a FormView.
Yes, It is possible.
I am demonstrating it with the Employee table
Use the following Sql Server script to create employee tabled named tbemployee
CREATE TABLE [dbo].[tbemployee](
[empid] [int] IDENTITY(1,1) NOT NULL,
[ename] [varchar](50) NULL,
[eadd] [varchar](50) NULL,
[esal] [int] NULL,
[edno] [int] NULL,
CONSTRAINT [PK_tbemployee] PRIMARY KEY CLUSTERED
(
[empid] ASC
)
) ON [PRIMARY]
GO
The source code for Inserting record into FormView is shown below:
FormView.aspx
<asp:FormView ID="FormView1" runat="server" DataKeyNames="empid"
oniteminserting="FormView1_ItemInserting" DefaultMode="Insert"
onmodechanging="FormView1_ModeChanging">
<InsertItemTemplate>
ename:
<asp:TextBox ID="txtename" runat="server" Text='<%# Bind("ename") %>' />
<br />
eadd:
<asp:TextBox ID="txteadd" runat="server" Text='<%# Bind("eadd") %>' />
<br />
esal:
<asp:TextBox ID="txtesal" runat="server" Text='<%# Bind("esal") %>' />
<br />
edno:
<asp:TextBox ID="txtedno" runat="server" Text='<%# Bind("edno") %>' />
<br />
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insert" />
<asp:LinkButton ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
<ItemTemplate>
empid:
<asp:Label ID="empidLabel" runat="server" Text='<%# Eval("empid") %>' />
<br />
ename:
<asp:Label ID="enameLabel" runat="server" Text='<%# Bind("ename") %>' />
<br />
eadd:
<asp:Label ID="eaddLabel" runat="server" Text='<%# Bind("eadd") %>' />
<br />
esal:
<asp:Label ID="esalLabel" runat="server" Text='<%# Bind("esal") %>' />
<br />
edno:
<asp:Label ID="ednoLabel" runat="server" Text='<%# Bind("edno") %>' />
<br />
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</ItemTemplate>
</asp:FormView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=gts7;Initial Catalog=dbemp14;Integrated Security=True;Pooling=False"
ProviderName="System.Data.SqlClient">
</asp:SqlDataSource>
and in the Code Behind of FormView.aspx page paste the following code:
FormView.aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
{
string ename, eadd,insertqry;
Int32 esal, edno;
ename = ((TextBox)(FormView1.FindControl("txtename"))).Text;
eadd = ((TextBox)(FormView1.FindControl("txtename"))).Text;
esal = Convert.ToInt32(((TextBox)(FormView1.FindControl("txtesal"))).Text);
edno = Convert.ToInt32(((TextBox)(FormView1.FindControl("txtedno"))).Text);
insertqry="insert tbemployee(ename,eadd,esal,edno) values(#ename,#eadd,#esal,#edno)";
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand(insertqry, con);
cmd.Parameters.Add("#ename", SqlDbType.VarChar, 50).Value = ename;
cmd.Parameters.Add("#eadd", SqlDbType.VarChar, 50).Value = eadd;
cmd.Parameters.Add("#esal", SqlDbType.Int).Value = esal;
cmd.Parameters.Add("#edno", SqlDbType.Int).Value = edno;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
FormView1.ChangeMode(FormViewMode.ReadOnly);
formbind();
}
public void formbind()
{
if (FormView1.AllowPaging == true)
{
SqlDataAdapter adp = new SqlDataAdapter("select * from tbemployee", con);
DataSet ds = new DataSet();
adp.Fill(ds);
Int32 totrecords = ds.Tables[0].Rows.Count;
Int32 currentpageindex = totrecords - 1;
FormView1.PageIndex = currentpageindex;
FormView1.DataSource = ds;
FormView1.DataBind();
}
else
{
SqlDataAdapter adp = new SqlDataAdapter("select * from tbemployee where empid in (select isnull(max(empid),0) from tbemployee)", con);
DataSet ds = new DataSet();
adp.Fill(ds);
FormView1.DataSource = ds;
FormView1.DataBind();
}
}
protected void FormView1_ModeChanging(object sender, FormViewModeEventArgs e)
{
FormView1.ChangeMode(e.NewMode);
formbind();
}
There is another solution that is much simpler IMHO.
Using the above (#SK-INFOPOINT) data, I would write my FormView1.aspx very much the same with only a couple of minor changes to default to "ReadOnly" mode and putting the SQL Insert and Select commands into the SQLAdapter to look like this:
FormView1.aspx
<asp:FormView ID="FormView1" runat="server" DataKeyNames="empid"
oniteminserting="FormView1_ItemInserting" DefaultMode="ReadOnly"
onmodechanging="FormView1_ModeChanging">
<InsertItemTemplate>
ename:
<asp:TextBox ID="txtename" runat="server" Text='<%# Bind("ename") %>' />
<br />
eadd:
<asp:TextBox ID="txteadd" runat="server" Text='<%# Bind("eadd") %>' />
<br />
esal:
<asp:TextBox ID="txtesal" runat="server" Text='<%# Bind("esal") %>' />
<br />
edno:
<asp:TextBox ID="txtedno" runat="server" Text='<%# Bind("edno") %>' />
<br />
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insert" />
<asp:LinkButton ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
<ItemTemplate>
empid:
<asp:Label ID="empidLabel" runat="server" Text='<%# Eval("empid") %>' />
<br />
ename:
<asp:Label ID="enameLabel" runat="server" Text='<%# Bind("ename") %>' />
<br />
eadd:
<asp:Label ID="eaddLabel" runat="server" Text='<%# Bind("eadd") %>' />
<br />
esal:
<asp:Label ID="esalLabel" runat="server" Text='<%# Bind("esal") %>' />
<br />
edno:
<asp:Label ID="ednoLabel" runat="server" Text='<%# Bind("edno") %>' />
<br />
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</ItemTemplate>
</asp:FormView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=gts7;Initial Catalog=dbemp14;Integrated Security=True;Pooling=False"
ProviderName="System.Data.SqlClient"
SelectCommand="select * from tbemployee"
InsertCommand="insert into tbemployee (ename,eadd,esal,edno) values (#ename, #eadd, #esal, #edno)">
</asp:SqlDataSource>
This allows the buttons and templates to do most of the functionality without a need to manually code the insertion and selecting. Then I would add only this in the Code Behind of FormView.aspx page the following code:
FormView.aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
FormView1.PageIndex = dv.Count - 1;
}
}
And you're displaying your bound new item in ReadOnly mode. And, if you add a simple paging template to your FormView, you can navigate up and down records however you please...
:)
-- Schnizzles