gridview editing and updating - c#

I got a gridview and there is hyperlink column which says update. Upon clicking that page will redirect to another page and particular row values will display in another gridview. and there the user need to edit 1 column and make it update and after that there is a button outside gridview which is send or accept , upon clicking it a mail should get generate it should take updated grid values and send it to he other user and page should get redirected to previous page.
aspx code of gridview
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="false" BackColor="White" BorderColor="#0061C1"
BorderStyle="None" CaptionAlign="Bottom" EmptyDataText="No Records Found"
Font-Names="Verdana" Font-Size="X-Small" ForeColor="#0061C1" Height="70px"
ShowFooter="True" ShowHeaderWhenEmpty="True" OnRowCommand="GridView1_RowCommand"
OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing"
onselectedindexchanged="GridView1_SelectedIndexChanged" OnRowUpdating="GridView1_RowUpdating"
Width="796px">
<Columns>
<asp:BoundField DataField="LeaveID" Visible="false">
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" HorizontalAlign="Center"
VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="10px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Applied By">
<ItemTemplate>
<asp:Label
ID="LoggedInUser" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Height="24px" Text='<%# Eval("LoggedInUser")%>' Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Begin Date">
<ItemTemplate>
<asp:Label
ID="BeginDate" runat="server" DataFormatString="{0:dd/MM/yyyy}"
Font-Names="Verdana" Text='<%# Eval("BeginDate","{0:dd/MM/yyyy}")%>' Font-Size="X-Small" Height="20px"
Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Date">
<ItemTemplate>
<asp:Label
ID="EndDate" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Height="20px" Text='<%# Eval("EndDate","{0:dd/MM/yyyy}")%>' Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Num of Days">
<ItemTemplate>
<asp:Label
ID="NumofDays" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Height="20px" Text='<%# Eval("NumofDays")%>' Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Type of Leave ">
<ItemTemplate>
<asp:Label
ID="LeaveType" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Height="20px" Text='<%# Eval("TypeofLeave")%>' Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label
ID="Status" runat="server" Font-Names="Verdana" Font-Size="X-Small"
ForeColor="Black" Height="20px" Text='<%# Eval("Status")%>' Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reason for Reject">
<ItemTemplate>
<asp:Label ID="RejectReason"
runat="server" Font-Names="Verdana" Font-Size="X-Small" ForeColor="Black"
Height="20px" Text='<%# Eval("RejectReason")%>' Enabled="true" Visible="true" Width="100px"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtRejectReason"
runat="server" Font-Names="Verdana" Font-Size="X-Small" ForeColor="Black"
Height="20px" Text='<%# Eval("RejectReason")%>' Enabled="true" Visible="true" Width="100px"></asp:TextBox>
</EditItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="LogdInUser" Visible="false" >
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" HorizontalAlign="Center"
VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="Manager" Visible="false" >
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" HorizontalAlign="Center"
VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
</asp:BoundField>
<asp:CommandField ShowEditButton="true" ButtonType="Button" EditText="Edit">
<ControlStyle Width="50" />
</asp:CommandField>
</Columns>
</asp:GridView>
i need to edit RejectReason Column.
cs page
protected void Page_Load(object sender, EventArgs e)
{
MTMSDTO objc = new MTMSDTO();
if (!IsPostBack)
{
int LeaveID = 0;
int.TryParse(Request.QueryString["LeaveID"], out LeaveID);
objc.LeaveID = LeaveID;
objc.RejectReason = TxtRejectReason.Text;
DataSet lapp = obj.GetLeaveApproved(objc);
DataView LApp = new DataView();
LApp.Table = lapp.Tables[0];
GridView1.DataSource = LApp;
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int LeaveID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox TxtRejectReason = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TxtRejectReason");
GridView1.EditIndex = -1;
GridView1.DataBind();
}
once i click edit button in gridview it shows no records
please help me

Try below code:
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowPaging ="true" ShowFooter = "true"
OnPageIndexChanging = "OnPaging" onrowediting="EditCustomer"
onrowupdating="UpdateCustomer" onrowcancelingedit="CancelEdit"
PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "CustomerID">
<ItemTemplate>
<asp:Label ID="lblCustomerID" runat="server"
Text='<%# Eval("CustomerID")%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCustomerID" Width = "40px"
MaxLength = "5" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField><asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name">
<ItemTemplate>
<asp:Label ID="lblContactName" runat="server"
Text='<%# Eval("ContactName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtContactName" runat="server"
Text='<%# Eval("ContactName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtContactName" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Company">
<ItemTemplate>
<asp:Label ID="lblCompany" runat="server"
Text='<%# Eval("CompanyName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCompany" runat="server"
Text='<%# Eval("CompanyName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCompany" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument = '<%# Eval("CustomerID")%>'
OnClientClick = "return confirm('Do you want to delete?')"
Text = "Delete" OnClick = "DeleteCustomer"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add"
OnClick = "AddNewCustomer" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
}
protected void AddNewCustomer(object sender, EventArgs e)
{
string CustomerID=((TextBox)GridView1.FooterRow.FindControl("txtCustomerID")).Text;
string Name = ((TextBox)GridView1.FooterRow.FindControl("txtContactName")).Text;
string Company = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
//Your Code here...
}
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
string CustomerID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblCustomerID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtContactName")).Text;
string Company = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtCompany")).Text;
//Your code here...
}
protected void DeleteCustomer(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from customers where " +
"CustomerID=#CustomerID;" +
"select CustomerID,ContactName,CompanyName from customers";
cmd.Parameters.Add("#CustomerID", SqlDbType.VarChar).Value
= lnkRemove.CommandArgument;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}

Use code when gridview edit,
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView gridView1= (GridView)sender;
// Change the row state
gridView1.Rows[e.NewEditIndex].RowState = DataControlRowState.Edit;
}
For Update(this is sample code)
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridView gv = (GridView)sender;
GridViewRow gvr = (GridViewRow)gv.Rows[e.RowIndex];
TextBox TxtRejectReason= (TextBox)gvr.FindControl("TxtRejectReason");
string s = TxtRejectReason.Text;
GridView.EditIndex = -1;
GridView.DataBind();
}

Related

How to update SelectedItem of Cascading dropdownlist in the SQL Database

I have 2 dropdownlist using Cascading method. But everytime the 1st item of 2nd dropdownlist gets updated in the database even if choose 2nd or 3rd item from the dropdownlist.
Selection from 2nd Dropdownlist
If I view my Database, it shows the Frame Hoist updated in Reason column instead of Number Punching m/c
Database image of updated data after selection
Please find below my .cs code
namespace Loss_Portal
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
populateData();
}
}
private void populateData()
{
// here code for populate person data
using (TrialEntities20 dc = new TrialEntities20())
{
var v = (from p in dc.Vehicle_Andon
where (p.Line_Name == DropDownList1.SelectedValue
&& p.Loss_Type == 9 && p.Date_Time == Date1.Value)
join s in dc.LOSS_TYPE_MASTER on p.Loss_Description equals s.Loss_Description
select new
{
p,
s.Loss_Description,
});
List<Vehicle_Andon> allP = new List<Vehicle_Andon>();
foreach (var i in v)
{
Vehicle_Andon p = new Vehicle_Andon();
p = i.p;
p.Loss_Description = i.Loss_Description;
allP.Add(p);
}
GridView1.DataSource = allP;
GridView1.DataBind();
}
}
private List<LOSS_TYPE_MASTER> populateState()
{
// here code for populate state
List<LOSS_TYPE_MASTER> all = new List<LOSS_TYPE_MASTER>();
using (TrialEntities20 dc = new TrialEntities20())
{
all = dc.LOSS_TYPE_MASTER.ToList();
}
return all;
}
public class ClassName
{
public string Station { get; set; }
public string Reason { get; set; }
}
private List<ClassName> populateCity(int Loss_Type)
{
List<ClassName> obj = new List<ClassName>();
using (TrialEntities20 dc = new TrialEntities20())
if (Loss_Type == 1)
{
obj = (from p in dc.LINE_CONFIGRATOR
where p.Line_Name == DropDownList1.SelectedValue && p.STATION == L2.Text
select new ClassName
{
Station = p.STATION,
Reason = p.Reason
}).ToList();
}
else if (Loss_Type == 6)
{
obj = (from p in dc.LINE_SKILL_CONFIG
where p.Line_Name == DropDownList1.SelectedValue && p.STATION == L2.Text
select new ClassName
{
Station = p.STATION,
Reason = p.Reason
}).ToList();
}
else if (Loss_Type == 8)
{
obj = (from p in dc.MATERIAL_SHORTAGE
where p.Line_Name == DropDownList1.SelectedValue && p.STATION == L2.Text
select new ClassName
{
Station = p.STATION,
Reason = p.Reason
}).ToList();
}
return obj;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
string loss_type = GridView1.DataKeys[e.NewEditIndex]["Loss_Type"].ToString();
string station = GridView1.DataKeys[e.NewEditIndex]["Station"].ToString();
// Edit Event
GridView1.EditIndex = e.NewEditIndex;
populateData();
// Here populate data for dropdown state
DropDownList ddLoss_DescriptionEdit = (DropDownList)GridView1.Rows[e.NewEditIndex].FindControl("ddLoss_Description");
if (ddLoss_DescriptionEdit != null)
{
ddLoss_DescriptionEdit.DataSource = populateState();
ddLoss_DescriptionEdit.DataTextField = "Loss_Description";
ddLoss_DescriptionEdit.DataValueField = "Loss_Type";
ddLoss_DescriptionEdit.DataBind();
ddLoss_DescriptionEdit.SelectedValue = loss_type;
}
string V = (GridView1.Rows[e.NewEditIndex].FindControl("txtStation") as Label).Text.Trim();
L2.Text = V;
DropDownList ddReasonEdit = (DropDownList)GridView1.Rows[e.NewEditIndex].FindControl("ddReason");
if (ddReasonEdit != null)
{
ddReasonEdit.DataSource = populateCity(Convert.ToInt32(loss_type));
ddReasonEdit.DataTextField = "Reason";
ddReasonEdit.DataValueField = "Station";
ddReasonEdit.DataBind();
ddReasonEdit.SelectedValue = station;
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
populateData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Here Update
int Master_ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["Master_ID"].ToString());
DropDownList ddLoss_DescriptionEdit = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddLoss_Description");
DropDownList ddReasonEdit = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddReason");
Label txtStationEdit = (Label)GridView1.Rows[e.RowIndex].FindControl("txtStation");
using (TrialEntities20 dc = new TrialEntities20())
{
Vehicle_Andon p = dc.Vehicle_Andon.Where(a => a.Master_ID.Equals(Master_ID)).FirstOrDefault();
if (p != null)
{
p.Loss_Type = Convert.ToInt32(ddLoss_DescriptionEdit.SelectedValue);
p.Loss_Description = ddLoss_DescriptionEdit.SelectedItem.ToString();
p.Reason = ddReasonEdit.SelectedItem.ToString();
dc.SaveChanges();
GridView1.EditIndex = -1;
populateData();
}
}
}
protected void ddLoss_Description_SelectedIndexChanged(object sender, EventArgs e)
{
// Populate city
{
string Loss_Type = ((DropDownList)sender).SelectedValue;
int rowIndex = GridView1.EditIndex;
DropDownList ddReasonEdit = (DropDownList)GridView1.Rows[rowIndex].FindControl("ddReason");
if (ddReasonEdit != null)
{
var v = populateCity(Convert.ToInt32(Loss_Type));
ddReasonEdit.DataSource = v;
ddReasonEdit.DataBind();
if (ddReasonEdit.Items.Count > 0)
{
ddReasonEdit.SelectedIndex = 0;
}
}
}
}
}
}
html code
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h3>Loss Portal</h3>
<div style="margin-left: 300px">
<asp:Label ID="Label1" runat="server" Text="Select Date :" Font-Bold="True" Font-Names="Arial Black" Font-Overline="False"></asp:Label>
<input id="Date1" runat="server" type="date" /><asp:RequiredFieldValidator ID="requiredfieldvalidator" runat="server" ControlToValidate="Date1" ErrorMessage="Date is Required" ForeColor="Red" style="z-index: 1; top: 109px; position: absolute; left: 720px" />
<br />
<br />
<asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Names="Arial Black" Text="Select Line :"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="Line_Name" DataValueField="Line_Name" Height="28px" Width="211px">
</asp:DropDownList><asp:RequiredFieldValidator ID="requiredfieldvalidator1" runat="server" ControlToValidate="DropDownList1" ErrorMessage="Select Line" ForeColor="Red" style="z-index: 1; top: 154px; position: absolute; left: 720px" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TrialConnectionString2 %>" SelectCommand="SELECT DISTINCT [Line_Name] FROM [Vehicle_Andon] ORDER BY [Line_Name]"></asp:SqlDataSource>
<br />
<br />
<asp:Button ID="Button1" runat="server" CssClass="btn-primary-active" OnClick="Button1_Click" Text="Submit" Width="180px" Height="31px" />
<br />
<br />
<asp:Label ID="L2" runat="server" Visible="false"/>
<br />
</div>
<div style="margin-left: 0px">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" onrowediting="GridView1_RowEditing" DataKeyNames="Loss_Type,Station,Master_ID"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowupdating="GridView1_RowUpdating" GridLines="None" ForeColor="#333333" >
<AlternatingRowStyle BackColor="White" HorizontalAlign="Center" VerticalAlign="Middle" />
<Columns>
<asp:TemplateField HeaderText="Master_ID " HeaderStyle-Width="30px" HeaderStyle-VerticalAlign="Middle" Visible="false">
<ItemTemplate>
<asp:Label Text='<%# Eval("Master_ID")%>' runat="server" Width="70px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="txtMaster_ID" Text='<%# Eval("Master_ID")%>' runat="server" />
</EditItemTemplate>
<HeaderStyle VerticalAlign="Middle" Width="30px"></HeaderStyle>
<HeaderStyle HorizontalAlign="Center" Width="30px"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Station No." HeaderStyle-Wrap="false" HeaderStyle-VerticalAlign="Middle" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label Text='<%# Eval("Station")%>' runat="server" Width="82px" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="txtStation" Text='<%# Eval("Station")%>' runat="server" />
</EditItemTemplate>
<HeaderStyle VerticalAlign="Middle" Wrap="False" HorizontalAlign="Justify"></HeaderStyle>
<HeaderStyle HorizontalAlign="Center" Width="30px"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Conveyor No." HeaderStyle-Wrap="false" HeaderStyle-VerticalAlign="Middle" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label Text='<%# Eval("Conveyor")%>' runat="server" Width="80px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="txtConveyor" Text='<%# Eval("Conveyor")%>' runat="server" />
</EditItemTemplate>
<HeaderStyle VerticalAlign="Middle" Wrap="False" HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Andon_PC " HeaderStyle-VerticalAlign="Middle" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label Text='<%# Eval("Andon_PC")%>' runat="server" Width="75px" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="txtAndon_PC" Text='<%# Eval("Andon_PC")%>' runat="server" />
</EditItemTemplate>
<HeaderStyle VerticalAlign="Middle" Wrap="False" HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Start_Time " HeaderStyle-VerticalAlign="Middle" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label Text='<%# Eval("Start_Time")%>' runat="server" Width="200px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="txtStart_Time" Text='<%# Eval("Start_Time")%>' runat="server" />
</EditItemTemplate>
<HeaderStyle VerticalAlign="Middle" Wrap="False" HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Close_Time " HeaderStyle-VerticalAlign="Middle" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label Text='<%# Eval("Close_Time")%>' runat="server" Width="200px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="txtClose_Time" Text='<%# Eval("Close_Time")%>' runat="server" />
</EditItemTemplate>
<HeaderStyle VerticalAlign="Middle" Wrap="False" HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duration" HeaderStyle-VerticalAlign="Middle" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label Text='<%# Eval("Duration")%>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="txtDuration" Text='<%# Eval("Duration")%>' runat="server" Width="55px"/>
</EditItemTemplate>
<HeaderStyle VerticalAlign="Middle" Wrap="False" HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Line_Name" HeaderStyle-VerticalAlign="Middle" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label Text='<%# Eval("Line_Name")%>' runat="server" Width="155px" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="txtLine_Name" Text='<%# Eval("Line_Name")%>' runat="server" />
</EditItemTemplate>
<HeaderStyle VerticalAlign="Middle" Wrap="False" HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Loss_Description" HeaderStyle-VerticalAlign="Middle" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="ltype" Text='<%# Eval("Loss_Description")%>' runat="server" Width="150px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:DropdownList ID="ddLoss_Description" DataTextField="Loss_Descripiton" DataValueField="Loss_Type"
runat="server" AutoPostBack="true" OnSelectedIndexchanged="ddLoss_Description_SelectedIndexChanged" >
</asp:DropdownList>
</EditItemTemplate>
<HeaderStyle VerticalAlign="Middle" Wrap="False" HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reason" HeaderStyle-VerticalAlign="Middle" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label Text='<%# Eval("Reason")%>' runat="server" Width="100px" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropdownList ID="ddReason" runat="server" DataTextField="Reason" DataValueField="Station">
</asp:DropdownList>
</EditItemTemplate>
<HeaderStyle VerticalAlign="Middle" Wrap="False" HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px">
<ItemTemplate>
<asp:ImageButton ImageUrl="imgs/edit.png" runat="server" CommandName="Edit" CommandArgument='<%#Eval("Master_ID") %>' ToolTip="Edit" Width="25px" Height="25px" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ImageUrl="imgs/save.png" runat="server" CommandName="Update" ToolTip="Update" CommandArgument='<%#Eval("Master_ID") %>' Width="25px" Height="25px" />
<asp:ImageButton ImageUrl="imgs/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="25px" Height="25px" />
</EditItemTemplate>
<HeaderStyle VerticalAlign="Middle" Wrap="False" HorizontalAlign="Center"></HeaderStyle>
</asp:TemplateField>
</Columns>
<EditRowStyle BorderColor="#99CCFF" BorderStyle="Dotted" HorizontalAlign="Center" VerticalAlign="Middle" BackColor="#3399FF" />
<FooterStyle BackColor="#507CD1" ForeColor="White" Font-Bold="True" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" VerticalAlign="Middle" BorderColor="#003366" BorderStyle="Solid" Width="50px" Wrap="False" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" BorderStyle="Solid" HorizontalAlign="Center" VerticalAlign="Middle" BorderColor="#003366" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" BorderStyle="Dotted" HorizontalAlign="Center" VerticalAlign="Middle" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" HorizontalAlign="Center" VerticalAlign="Middle" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:GridView>
</div>
</asp:Content>
I'm new to Linq query and I need to complete my project.
Please, could someone help ?

How to get the row index of a dynamically created asp.net GridView?

How to get the row index of a dynamically created asp.net GridView so that I can edit the record in a text box outside the GridView.
How to get the row index of a dynamically created asp.net GridView so that I can edit the record in a text box outside the GridView.
This is the GridView:
<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="RefID">
<ItemTemplate>
<asp:Label ID="lbl_Refid" runat="server" Text='<%# Eval("Refid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="lbl_date" runat="server" Text='<%# Eval("Date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name Of Company">
<ItemTemplate>
<asp:Label ID="lbl_noc" runat="server" Text='<%# Eval("Name_Of_Company") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact/Email">
<ItemTemplate>
<asp:Label ID="lbl_wht_do" runat="server" Text='<%# Eval("Contact") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:Label ID="lbl_wht_do" runat="server" Text='<%# Eval("Remarks") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="btn_edit" runat="server" `enter code here` Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<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>
<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCommand = "OnRowCommand">
Use
OnRowCommand = "OnRowCommand"
Now when any action happen on the grid the OnRowCommand event is executed.
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}
More Info
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
and your method
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

In my Asp.net App, i have a GridView and i generate the data of column[6] by myself using code behind.
by looking at the code below, i have a footer for my gridview. and the problem is my text for column[6] won't appear if i use footer.
If i delete the footertext code, then my text for column[6] is appear. what is the problem? both of the code cant use togather? i already set ShowFooter="True"
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < (this.GridView1.Rows.Count); i++)
{
this.GridView1.Rows[i].Cells[6].Text = "testing";
//GridView1.Columns[1].FooterText ="footer 1";
}
}
.aspx
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4"
ForeColor="#333333" GridLines="None" ShowFooter="True"
onrowdatabound="GridView1_RowDataBound">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:BoundField DataField="reportDate" HeaderText="Report Date" dataformatstring="{0:dd MMMM yyyy}" SortExpression="reportDate" />
<asp:BoundField DataField="sponsorBonus" HeaderText="Sponsor Bonus" dataformatstring="{0:0.00}" SortExpression="sponsorBonus" HtmlEncode="False" />
<asp:BoundField DataField="pairingBonus" HeaderText="Pairing Bonus" HtmlEncode="False" SortExpression="pairingBonus" dataformatstring="{0:c}" />
<asp:BoundField DataField="staticBonus" HeaderText="Static Bonus" SortExpression="staticBonus" />
<asp:BoundField DataField="leftBonus" HeaderText="Left Bonus" SortExpression="leftBonus" />
<asp:BoundField DataField="rightBonus" HeaderText="Right Bonus" SortExpression="rightBonus" />
<asp:BoundField HeaderText="Total" SortExpression="total" >
<ItemStyle Width="100px" />
</asp:BoundField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
Sample Code: To set Footer text programatically
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = grdTotal.ToString("c");
}
}
UPDATED CODE:
decimal sumFooterValue = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string sponsorBonus = ((Label)e.Row.FindControl("Label2")).Text;
string pairingBonus = ((Label)e.Row.FindControl("Label3")).Text;
string staticBonus = ((Label)e.Row.FindControl("Label4")).Text;
string leftBonus = ((Label)e.Row.FindControl("Label5")).Text;
string rightBonus = ((Label)e.Row.FindControl("Label6")).Text;
decimal totalvalue = Convert.ToDecimal(sponsorBonus) + Convert.ToDecimal(pairingBonus) + Convert.ToDecimal(staticBonus) + Convert.ToDecimal(leftBonus) + Convert.ToDecimal(rightBonus);
e.Row.Cells[6].Text = totalvalue.ToString();
sumFooterValue += totalvalue;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = sumFooterValue.ToString();
}
}
In .aspx Page
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4"
ForeColor="#333333" GridLines="None" ShowFooter="True"
onrowdatabound="GridView1_RowDataBound">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:TemplateField HeaderText="Report Date" SortExpression="reportDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("reportDate") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("reportDate", "{0:dd MMMM yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sponsor Bonus" SortExpression="sponsorBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("sponsorBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("sponsorBonus", "{0:0.00}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pairing Bonus" SortExpression="pairingBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("pairingBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("pairingBonus", "{0:c}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Static Bonus" SortExpression="staticBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Left Bonus" SortExpression="leftBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Right Bonus" SortExpression="rightBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" SortExpression="total">
<EditItemTemplate>
<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltotal" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
protected void gvBill_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
Total += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "InvMstAmount"));
else if (e.Row.RowType == DataControlRowType.Footer)
e.Row.Cells[7].Text = String.Format("{0:0}", "<b>" + Total + "</b>");
}
This can be achieved through LINQ with grouping, here a list of items pointed as a data source to the actual grid view.
Sample pseudo code which could help coding the actual.
var tabelDetails =(from li in dc.My_table
join m in dc.Table_One on li.ID equals m.ID
join c in dc.Table_two on li.OtherID equals c.ID
where //Condition
group new { m, li, c } by new
{
m.ID,
m.Name
} into g
select new
{
g.Key.ID,
Name = g.Key.FullName,
sponsorBonus= g.Where(s => s.c.Name == "sponsorBonus").Count(),
pairingBonus = g.Where(s => s.c.Name == "pairingBonus").Count(),
staticBonus = g.Where(s => s.c.Name == "staticBonus").Count(),
leftBonus = g.Where(s => s.c.Name == "leftBonus").Count(),
rightBonus = g.Where(s => s.c.Name == "rightBonus").Count(),
Total = g.Count() //Row wise Total
}).OrderBy(t => t.Name).ToList();
tabelDetails.Insert(tabelDetails.Count(), new //This data will be the last row of the grid
{
Name = "Total", //Column wise total
sponsorBonus = tabelDetails.Sum(s => s.sponsorBonus),
pairingBonus = tabelDetails.Sum(s => s.pairingBonus),
staticBonus = tabelDetails.Sum(s => s.staticBonus),
leftBonus = tabelDetails.Sum(s => s.leftBonus),
rightBonus = tabelDetails.Sum(s => s.rightBonus ),
Total = tabelDetails.Sum(s => s.Total)
});
<asp:TemplateField HeaderText="ExEmp" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
FooterStyle-BackColor="BurlyWood" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox ID="txtNoOfExEmp" runat="server" CssClass="form-control input-sm m-bot15"
Font-Bold="true" onkeypress="return isNumberKey(event)" Text='<%#Bind("ExEmp") %>'></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="50px" />
<FooterTemplate>
<asp:Label ID="lblTotNoOfExEmp" Font-Bold="true" runat="server" Text="0" CssClass="form-label"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
private void TotalExEmpOFMonth()
{
Label lbl_TotNoOfExEmp = (Label)GrdPFRecord.FooterRow.FindControl("lblTotNoOfExEmp");
/*Sum of the Total Amount Of month*/
foreach (GridViewRow gvr in GrdPFRecord.Rows)
{
TextBox txt_NoOfExEmp = (TextBox)gvr.FindControl("txtNoOfExEmp");
lbl_TotNoOfExEmp.Text = (Convert.ToDouble(txt_NoOfExEmp.Text) + Convert.ToDouble(lbl_TotNoOfExEmp.Text)).ToString();
lbl_TotNoOfExEmp.Text = string.Format("{0:F0}", Decimal.Parse(lbl_TotNoOfExEmp.Text));
}
}
int total = 0;
protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotal");
lblamount.Text = total.ToString();
}
}
/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);
private void SumOFEPFWages(GridView grd)
{
Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
/*Sum of the total Amount of the day*/
foreach (GridViewRow gvr in grd.Rows)
{
Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
}
}

how to edit and update row values in grid view?

I have a gridview like this :
<asp:GridView ID="gvProducts" runat="server" AutoGenerateEditButton="True" AutoGenerateColumns="False"
OnRowEditing="gvProducts_RowEditing" OnRowUpdating="gvProducts_RowUpdating" CellPadding="4"
ForeColor="#333333" GridLines="None">
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblPID" runat="server" Text="Product ID"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblProdID" runat="server" Text='<%#Eval("ProductID")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProdID" runat="server" Text='<%#Eval("ProductID")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblPName" runat="server" Text="Product Name"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblProdName" runat="server" Text='<%#Eval("ProductName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProdName" runat="server" Text='<%#Eval("ProductName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
and here is the code behind page
protected void gvProducts_RowEditing(object sender, GridViewEditEventArgs e)
{
gvProducts.EditIndex = e.NewEditIndex;
}
protected void gvProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int i = e.RowIndex;
object control = gvProducts.Rows[i].FindControl("txtProdID");
//i want to access the new value from the object "control" but i m getting the previous value only
}
try this
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtProdID = (TextBox)gvProducts.Rows[e.RowIndex].FindControl("txtProdID");
TextBox txtProdName = (TextBox)gvProducts.Rows[e.RowIndex].FindControl("txtProdName");
//Call update method
Product.Update(txtProdId,txtProdName);
gvProducts.EditIndex = -1;
//Refresh the gridviwe
BindGrid();
}
You need to check the e.NewValues dictionary for updated data.
I've a sample below, the GridView Template is bound to CategoryName.
OnRowUpdating is fired when the 'Edit' button is clicked.
In the RowUpdating event handler, it fetches the CategoryName data to which the textbox is bound to.
Note: Instead of using TextBox in normal mode use Labels.
<asp:GridView ID='GridView1' runat='server' DataKeyNames='CategoryID' OnRowUpdating='HandleOnGridViewRowUpdating'
DataSourceID='ObjectDataSource1' AutoGenerateColumns='false'>
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID='CategoryName' Text='Category' runat='server'></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID='CategoryNameTextbox' Text='<%# Bind("CategoryName") %>' runat='server'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code-behind:
public void HandleOnGridViewRowUpdating(object sender, GridViewUpdateEventArgs e)
{
if (e.NewValues["CategoryName"] != null)
{
String newCategoryName = e.NewValues["CategoryName"].ToString();
// process the data;
}
}

row.Cells[4].Text returns nothing in GridView1_SelectedIndexChanged?

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;

Categories