Check for column and bind grid if exists or not - c#

How to bind data to itemtemplate of gridview at RowDataBound event. I am using a gridview and below is the code for that grid view.
<asp:GridView ID="gvCoreUtilization" runat="server" BackColor="White" BorderColor="#cEcFcE"
BorderStyle="Solid" BorderWidth="1px" CellPadding="4" ForeColor="Black" OnRowCreated="grdPivot3_RowCreated"
AutoGenerateColumns="false" OnRowDataBound="grdCoreUtilization_RowDataBound">
<RowStyle BackColor="#F7F7DE" />
<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblRoleID" Text='<%#Eval("RoleId") %>' runat="server" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
SupervisorName
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblSupervisorName" Text='<%#Eval("SupervisorName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
UserECode
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblUserECode" Text='<%#Eval("UserECode") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
UserName
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblUserName" Text='<%#Eval("UserName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Designation
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblDesignation" Text='<%#Eval("Designation") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
L & D Training%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblLDTraining" Text='<%#Eval("L & D Training%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Non Production%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblNonProduction" Text='<%#Eval("Non Production%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Process Support%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblProcessSupport" Text='<%#Eval("Process Support%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Process Training%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblProcessTraining" Text='<%#Eval("Process Training%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Production%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblProduction" Text='<%#Eval("Production%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
System Downtime%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblSystemDowntime" Text='<%#Eval("System Downtime%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Grand Total%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblGrandTotal" Text='<%#Eval("Grand Total%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here i want to remove EVAl for binding the data to itemtemplate. In place of this i want to check weather
If all the Column exists in the dataset/Datatable or not which is mentioned in the Gridview.
If all Column exists then bind that column to appropriate Itemtemplate .
If All column not exist then display and bind only available column and hide the not available column.
Query used:-
Select RoleId,SuperVisorName,Userecode,Username,Designation,TimeSpent,ActivityName
from CoreUtilizationForRole1 where roleid=3
After executing the above query, i am doing a pivot on Activity column from c# and those columns are "L & D Training%","Non Production%","Process Support%","Process Training%","Production%","System Downtime%","Grand Total%" which i am binding on ItemTemplate.

Try this on each of your template field.
Set Visible property as following...
Visible='<%# !String.IsNullOrEmpty(Eval("RoleId").ToString()) %>'

if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.Label lblRoleNo = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblRoleId");
System.Web.UI.WebControls.Label lblSupervisorName = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblSupervisorName");
System.Web.UI.WebControls.Label lblUserECode = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblUserECode");
System.Web.UI.WebControls.Label lblUserName = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblUserName");
System.Web.UI.WebControls.Label lblDesignation = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblDesignation");
System.Web.UI.WebControls.Label lblLDTraining = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblLDTraining");
System.Web.UI.WebControls.Label lblNonProduction = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblNonProduction");
System.Web.UI.WebControls.Label lblProcessSupport = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblProcessSupport");
System.Web.UI.WebControls.Label lblProcessTraining = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblProcessTraining");
System.Web.UI.WebControls.Label lblProduction = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblProduction");
System.Web.UI.WebControls.Label lblSystemDowntime = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblSystemDowntime");
System.Web.UI.WebControls.Label lblGrandTotal = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblGrandTotal");
//Checking weather Columns exist in the Pivot or not
var dataRow = (DataRowView)e.Row.DataItem;
var columnNameToCheck = "L & D Training%";
var checkTraining = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheck, StringComparison.InvariantCultureIgnoreCase));
if (checkTraining)
{
// Property available
lblLDTraining.Text = (DataBinder.Eval(e.Row.DataItem, "L & D Training%")).ToString();
}
else
{
lblLDTraining.Visible = false;
}
var columnNonProduction = "Non Production%";
var checkNonProduction = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNonProduction, StringComparison.InvariantCultureIgnoreCase));
if (checkNonProduction)
{
// Property available
lblNonProduction.Text = (DataBinder.Eval(e.Row.DataItem, "Non Production%")).ToString();
}
else
{
lblNonProduction.Visible = false;
}
var columnProcessSupport = "Process Support%";
var checkProcessSupport = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnProcessSupport, StringComparison.InvariantCultureIgnoreCase));
if (checkProcessSupport)
{
// Property available
lblProcessSupport.Text = (DataBinder.Eval(e.Row.DataItem, "Process Support%")).ToString();
}
else
{
lblProcessSupport.Visible = false;
}
var columnProcessTraining = "Process Training%";
var checkProcesstraining = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnProcessTraining, StringComparison.InvariantCultureIgnoreCase));
if (checkProcesstraining)
{
// Property available
lblProcessTraining.Text = (DataBinder.Eval(e.Row.DataItem, "Process Training%")).ToString();
}
else
{
lblProcessTraining.Visible = false;
}
var columnProduction = "Production%";
var checkProduction = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnProduction, StringComparison.InvariantCultureIgnoreCase));
if (checkProduction)
{
// Property available
lblProduction.Text = (DataBinder.Eval(e.Row.DataItem, "Production%")).ToString();
}
else
{
lblProduction.Visible = false;
}
var columnSystemDownTime = "System Downtime%";
var checkSystemDownTime = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnSystemDownTime, StringComparison.InvariantCultureIgnoreCase));
if (checkSystemDownTime)
{
// Property available
lblSystemDowntime.Text = (DataBinder.Eval(e.Row.DataItem, "System Downtime%")).ToString();
}
else
{
lblSystemDowntime.Visible = false;
}
var columnGrandTotal = "Grand Total%";
var checkGrandTotal = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnGrandTotal, StringComparison.InvariantCultureIgnoreCase));
if (checkGrandTotal)
{
// Property available
lblGrandTotal.Text = (DataBinder.Eval(e.Row.DataItem, "Grand Total%")).ToString();
}
else
{
lblGrandTotal.Visible = false;
}
var columnNameToCheckRoleID = "RoleId";
var checkRoleID = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheckRoleID, StringComparison.InvariantCultureIgnoreCase));
if (checkRoleID)
{
// Property available
lblRoleNo.Text = (DataBinder.Eval(e.Row.DataItem, "RoleId")).ToString();
}
else
{
lblRoleNo.Visible = false;
}
var columnNameToCheckSupervisorName = "SupervisorName";
var checkSupervisorName = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheckSupervisorName, StringComparison.InvariantCultureIgnoreCase));
if (checkSupervisorName)
{
// Property available
lblSupervisorName.Text = (DataBinder.Eval(e.Row.DataItem, "SupervisorName")).ToString();
}
else
{
lblSupervisorName.Visible = false;
}
var columnNameToCheckUserECode = "UserECode";
var checkUserECode = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheckUserECode, StringComparison.InvariantCultureIgnoreCase));
if (checkUserECode)
{
// Property available
lblUserECode.Text = (DataBinder.Eval(e.Row.DataItem, "UserECode")).ToString();
}
else
{
lblUserECode.Visible = false;
}
var columnNameToCheckUserName = "UserName";
var checkUserName = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheckUserName, StringComparison.InvariantCultureIgnoreCase));
if (checkUserName)
{
// Property available
lblUserName.Text = (DataBinder.Eval(e.Row.DataItem, "UserName")).ToString();
}
else
{
lblUserName.Visible = false;
}
var columnNameToCheckDesignation = "Designation";
var checkDesignation = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheckDesignation, StringComparison.InvariantCultureIgnoreCase));
if (checkDesignation)
{
// Property available
lblDesignation.Text = (DataBinder.Eval(e.Row.DataItem, "Designation")).ToString();
}
else
{
lblDesignation.Visible = false;
}
//Changing color of the Pivot Data
if (Convert.ToInt32(lblRoleNo.Text.ToString()) == 2)
{
e.Row.BackColor = System.Drawing.Color.GreenYellow;
}
if (Convert.ToInt32(lblRoleNo.Text.ToString()) == 3)
{
e.Row.BackColor = System.Drawing.Color.Cyan;
}
if (Convert.ToInt32(lblRoleNo.Text.ToString()) == 4)
{
e.Row.BackColor = System.Drawing.Color.Orange;
}
if (Convert.ToInt32(lblRoleNo.Text.ToString()) == 5)
{
e.Row.BackColor = System.Drawing.Color.Pink;
}
}

this code provide you to hide particular cell from code behind if the value is blank...
Protected Sub gvCoreUtilization_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvCoreUtilization.RowDataBound
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim olblRoleID As New Label
Dim olblSupervisorName As New Label
Dim olblUserECode As New Label
Dim olblUserName As New Label
Dim olblDesignation As New Label
Dim olblLDTraining As New Label
Dim olblNonProduction As New Label
Dim olblProcessSupport As New Label
Dim olblProcessTraining As New Label
Dim olblProduction As New Label
Dim olblSystemDowntime As New Label
Dim olblGrandTotal As New Label
olblRoleID = CType(e.Row.FindControl("lblRoleID"), Label)
olblSupervisorName = CType(e.Row.FindControl("lblSupervisorName"), Label)
olblUserECode = CType(e.Row.FindControl("lblUserECode"), Label)
olblUserName = CType(e.Row.FindControl("lblUserName"), Label)
olblDesignation = CType(e.Row.FindControl("lblDesignation"), Label)
olblLDTraining = CType(e.Row.FindControl("lblLDTraining"), Label)
olblNonProduction = CType(e.Row.FindControl("lblNonProduction"), Label)
olblProcessSupport = CType(e.Row.FindControl("lblProcessSupport"), Label)
olblProcessTraining = CType(e.Row.FindControl("lblProcessTraining"), Label)
olblProduction = CType(e.Row.FindControl("lblProduction"), Label)
olblSystemDowntime = CType(e.Row.FindControl("lblSystemDowntime"), Label)
olblGrandTotal = CType(e.Row.FindControl("lblGrandTotal"), Label)
If CType(DataBinder.Eval(e.Row.DataItem, "RoleId"), String) = "" Then
olblRoleID.Visible = False
Else
olblRoleID.Text = DataBinder.Eval(e.Row.DataItem, "RoleId")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "SupervisorName"), String) = "" Then
olblSupervisorName.Visible = False
Else
olblSupervisorName.Text = DataBinder.Eval(e.Row.DataItem, "SupervisorName")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "UserECode"), String) = "" Then
olblUserECode.Visible = False
Else
olblUserECode.Text = DataBinder.Eval(e.Row.DataItem, "UserECode")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "UserName"), String) = "" Then
olblUserName.Visible = False
Else
olblUserName.Text = DataBinder.Eval(e.Row.DataItem, "UserName")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Designation"), String) = "" Then
olblDesignation.Visible = False
Else
olblDesignation.Text = DataBinder.Eval(e.Row.DataItem, "Designation")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "L & D Training"), String) = "" Then
olblLDTraining.Visible = False
Else
olblLDTraining.Text = DataBinder.Eval(e.Row.DataItem, "L & D Training")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Non Production"), String) = "" Then
olblNonProduction.Visible = False
Else
olblNonProduction.Text = DataBinder.Eval(e.Row.DataItem, "Non Production")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Process Support"), String) = "" Then
olblProcessSupport.Visible = False
Else
olblProcessSupport.Text = DataBinder.Eval(e.Row.DataItem, "Process Support")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Process Training"), String) = "" Then
olblProcessTraining.Visible = False
Else
olblProcessTraining.Text = DataBinder.Eval(e.Row.DataItem, "Process Training")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Production"), String) = "" Then
olblProduction.Visible = False
Else
olblProduction.Text = DataBinder.Eval(e.Row.DataItem, "Production")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "System Downtime"), String) = "" Then
olblSystemDowntime.Visible = False
Else
olblSystemDowntime.Text = DataBinder.Eval(e.Row.DataItem, "System Downtime")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Grand Total"), String) = "" Then
olblGrandTotal.Visible = False
Else
olblGrandTotal.Text = DataBinder.Eval(e.Row.DataItem, "Grand Total")
End If
End If
Catch ex As Exception
General.LogException(ex)
End Try
End Sub
And if you want to hide entire column in grid please follow below step
1) Create View state property on page for every column
Property RoleId() As boolen
Get
If IsNothing(Me.ViewState("RoleId")) Then Me.ViewState("RoleId") = false
Return CType(Me.ViewState("RoleId"), Boolean)
End Get
Set(ByVal value As Boolean)
Me.ViewState("RoleId") = value
End Set
End Property
2) Loop throw Data-set for every column for each row and check value exist or not and set this property ,finally you have property with value true or false and you can find which column need to display in grid.
3)then you can easily hide column of grid.
if Me.RoleId= True then
'Write code to Display
else
'Write code to Hide
end if

Related

Why Asp:GridView calls button click method in server side?

In my case i have asp:gridview with OnRowCommand calls server method but when i try to refresh my page manually then it also calls OnRowCommand method, i don't know where is the actual problem.
My Code:.aspx
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" OnSelectedIndexChanged="CUG_OnSelectedIndexChanged" OnRowCommand="CugSubmit_onserverclick1" EnableViewState="true"BorderStyle="Solid" BorderColor="Gray" BorderWidth="1px" EditRowStyle-BorderStyle="Solid" EditRowStyle-BorderWidth="1px" EditRowStyle-BorderColor="Gray" HeaderStyle-BorderStyle="Solid" HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="Gray" RowStyle-BorderStyle="Solid" RowStyle-BorderColor="Gray" RowStyle-BorderWidth="1px" EmptyDataRowStyle-BorderStyle="Solid" EmptyDataRowStyle-BorderColor="Black" EmptyDataRowStyle-BorderWidth="1px" SortedAscendingHeaderStyle-BorderStyle="Solid" SortedAscendingHeaderStyle-BorderColor="Black" SortedAscendingHeaderStyle-BorderWidth="1px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Driver ID">
<ItemTemplate>
<asp:Label ID="lbl_Dri_Name" runat="server" Text='<%# Eval("VehicleNo") %>' Visible="false"></asp:Label>
<asp:TextBox ID="Dri_Name" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dedicated">
<ItemTemplate>
<asp:Label ID="lbl_Vehitype" runat="server" Text='<%# Eval("VehicleType") %>' Visible="false"></asp:Label>
<asp:CheckBox ID="Vehitype" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="ProcessThis" Text="Submit" />
<asp:ButtonField CommandName="Select" ItemStyle-Width="30" Text="delete" HeaderText="Delete" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
</ItemTemplate>
<FooterStyle HorizontalAlign="left" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add Row" onclick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns></asp:gridview>
My code:.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetCUGList();
}
}
protected void CugSubmit_onserverclick1(object sender, GridViewCommandEventArgs e)
{
DL.CustomerProfile ObjInput = new CustomerProfile();
BL.CustomerInputBL ObjCustomerInputBL = new CustomerInputBL();
if (e.CommandName == "ProcessThis")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
TextBox textBox = row.FindControl("Dri_Name") as TextBox;
CheckBox chk = row.FindControl("Vehitype") as CheckBox;
ObjInput.CustId = HttpContext.Current.Session["VidStr"].ToString();
ObjInput.CustName = HttpContext.Current.Session["FirstName"].ToString();
ObjInput.VehiNo = textBox.Text;
ObjInput.Update = "Insert";
if (chk.Checked == true)
{
ObjInput.VehiChk = 1;
}
else
{
ObjInput.VehiChk = 0;
}
string URL = "http://*****/CustomerServices.svc/CUGList/";
string OutStatus = ObjCustomerInputBL.GetConnection(ObjInput, URL);
var serializer = new JavaScriptSerializer();
//AllTypeDetails.Value = OutStatus;
DataSet data = JsonConvert.DeserializeObject<DataSet>(OutStatus);
string ds = data.Tables[0].Rows[0]["ErrorMessage"].ToString();
if (ds == "already exist")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number has already registered')", true);
GetCUGList();
}
else if (ds == "Not Use")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number is not in freightX')", true);
GetCUGList();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Insert Request Sent to Admin')", true);
GetCUGList();
}
}
AddNewRowToGrid();
}
else if (e.CommandName == "ProcessThisUpdate")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
TextBox textBox = row.FindControl("Dri_Name") as TextBox;
CheckBox chk = row.FindControl("Vehitype") as CheckBox;
ObjInput.CustId = HttpContext.Current.Session["VidStr"].ToString();
ObjInput.CustName = HttpContext.Current.Session["FirstName"].ToString();
ObjInput.Update = "Update";
ObjInput.VehiNo = textBox.Text;
if (chk.Checked == true)
{
ObjInput.VehiChk = 1;
}
else
{
ObjInput.VehiChk = 0;
}
string URL = "http://*******/CustomerServices.svc/CUGList/";
string OutStatus = ObjCustomerInputBL.GetConnection(ObjInput, URL);
var serializer = new JavaScriptSerializer();
//AllTypeDetails.Value = OutStatus;
DataSet data = JsonConvert.DeserializeObject<DataSet>(OutStatus);
string ds = data.Tables[0].Rows[0]["ErrorMessage"].ToString();
if (ds == "already exist")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number has already registered')", true);
GetCUGList();
}
else if (ds == "Not Use")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number is not in freightX')", true);
GetCUGList();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Update Request Sent to Admin')", true);
GetCUGList();
}
}
}
}

edit row in Gridview by button

I have a Gridview like this
<div id="gridScroll" style="width: 100%; height: calc(100vh - 310px); overflow: auto">
<asp:GridView ID="gridRoles" runat="server" Width="100%" AutoGenerateColumns="False" Font-Names="Arial" PageSize="12"
Font-Size="11pt" CssClass="textGrid" AlternatingRowStyle-BackColor="#CED8F6" HeaderStyle-BackColor="#F2F2F2"
AllowPaging="True" OnPageIndexChanged ="IndexChanged" OnPageIndexChanging ="PageChange" OnRowDataBound="gridroles_RowDataBound" OnRowEditing="editRow">
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" text="Edit" OnCliendClick="btnEditClick()" />
<asp:Button ID="btnAdd" runat="server" text="Add" OnClientClick="btnAddClick()" Visible="false"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="First Name" HeaderText="First Name" />
<asp:BoundField DataField="Last Name" HeaderText="Last Name" /
</Columns>
<HeaderStyle BackColor="#A9BCF5" />
<AlternatingRowStyle BackColor="#CED8F6" />
</asp:GridView>
</div>
The data is bound from the back end
DataTable dt = new DataTable();
dt.Columns.Add("Action");
dt.Columns.Add("First Name", typeof(string));
dt.Columns.Add("Last Name", typeof(string));
for (int i = 0; i < credentials.Count; i++)
{
DataRow row1 = dt.NewRow();
row1["First Name"] = credentials[i].FirstName.ToString();
row1["Last Name"] = credentials[i].LastName.ToString();
dt.Rows.Add(row1);
}
DataRow row2 = dt.NewRow();
dt.Rows.Add(row2);
gridRoles.DataSource = dt;
gridRoles.DataBind();
I have this method btnEditClick() that is called when the Edit button is clicked.
function btnEditClick() {
var target = event.target || event.srcElement;
target.id = "btnEdit";
target.style.display = 'none';
var cancel = document.getElementById("btnCancel");
if (cancel != null)
cancel.click();
var row = target.parentElement.parentElement;
var cells = row.cells;
var hdn = document.createElement("input");
hdn.type = "hidden";
hdn.id = "hdnId";
hdn.name = "hdnId";
hdn.value = cells[1].innerHTML;
cells[0].appendChild(hdn);
for (var i = 2; i < 11; i++) {
//2, 3,4 , 10 textboxes
if (i == 2 || i == 3 || i == 4 || i == 10) {
var txt = document.createElement("input");
txt.value = cells[i].innerHTML;
txt.alt = cells[i].innerHTML;
txt.name = "txt" + i;
txt.maxLength = 50;
txt.style.width = "95%";
cells[i].innerHTML = "";
cells[i].appendChild(txt);
}
//this is for a dropdownlist for other columns in gridview I will add
if (i >= 5 && i < 10) {
var ddl = document.createElement("select");
var option = document.createElement("option");
option.setAttribute("value", "TRUE");
option.innerHTML = "TRUE";
ddl.appendChild(option);
var option2 = document.createElement("option");
option2.setAttribute("value", "FALSE");
option2.innerHTML = "FALSE";
ddl.appendChild(option2);
if (cells[i].innerHTML == "False") {
ddl.selectedIndex = 1;
}
ddl.name = "DDL" + i;
ddl.alt = cells[i].innerHTML;
cells[i].innerHTML = "";
cells[i].appendChild(ddl);
}
}
var btnCancel = document.createElement("button");
var Confirm = document.getElementById("cph_body_btnConfirm");
btnCancel.textContent = "Cancel";
btnCancel.id = "btnCancel";
btnCancel.onclick = cancelClick;
cells[0].appendChild(Confirm);
cells[0].appendChild(btnCancel);
return false;
The problem is, when I click the edit button it appears to go into edit mode. All the correct textboxes and dropdownlists show up but after about a second it disappears and the row goes back to what it looked like before the button was clicked. I'm not sure if the Gridview is refreshing itself. What would cause this problem?

DataTable in ViewState is Returning Deleted Rows

I am currently working on a dynamic gridview that will allow a user to add or delete rows in order to be saved as database entries later on.
My gridview markup is as such:
<asp:UpdatePanel ID="upAirporterSchedule" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvAirporterSchedule" runat="server" ShowFooter="true" AutoGenerateColumns="false" CssClass="table table-striped table-bordered table-hover dataTable no-footer" OnRowDataBound="gvAirporterSchedule_RowDataBound" OnRowCommand="gvAirporterSchedule_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Location" ItemStyle-Width="25%">
<ItemTemplate>
<asp:DropDownList ID="ddlScheduleLoc" runat="server" CssClass="form-control"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Start Date">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterStartDate" runat="server" CssClass="form-control date-picker" Text='<%# Eval("StartDateColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Date">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterEndDate" runat="server" CssClass="form-control date-picker" Text='<%# Eval("EndDateColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Departure Time">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterDepTime" runat="server" CssClass="form-control time-picker" Text='<%# Eval("DeptTimeColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-clock-o"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duration">
<ItemTemplate>
<asp:TextBox ID="tbxAirporterDuration" runat="server" CssClass="form-control" Text='<%# Eval("DurationColumn") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button ID="btnDel" runat="server" CssClass="btn btn-default" Text="Delete" CommandName="DeleteRow" />
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" CssClass="btn btn-default" Text="Add Entry" CommandName="AddRow" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Aside from this grid, I have some other fields in the user control. When I go to save, the user will click a button at the bottom of the user control which will package up the form fields above it and the grid into some classes and shoot this off to the database code to add/update this data.
Page.Validate("AirporterFares");
if (Page.IsValid)
{
try
{
// Save trip information.
SysVarService.SharedRideTrip trip = new SysVarService.SharedRideTrip();
if (_tripID > 0)
trip = Global.sysVarService.GetSharedRideTripByID(_tripID);
trip.isVisible = 1;
trip.productType = ReservationService.ProductType.TOUR;
trip.originStopID = Convert.ToInt32(ddlOrigin.SelectedValue.ToString());
trip.destinationStopID = Convert.ToInt32(ddlDestination.SelectedValue.ToString());
trip.defaultDuration = 0;
trip.effectiveDate = DateTime.Parse(tbxAirporterEffDate.Text.Trim());
trip.startTimeOfDay = new DateTime(trip.effectiveDate.Year, trip.effectiveDate.Month, trip.effectiveDate.Day, 1, 1, 1);
trip.endTimeOfDay = new DateTime(trip.effectiveDate.Year, trip.effectiveDate.Month, trip.effectiveDate.Day, 1, 1, 1);
// Save the two fare information.
SysVarService.SharedRideTrip_ShuttleFare aFare = new SysVarService.SharedRideTrip_ShuttleFare()
{
effectiveDate = trip.effectiveDate,
effectiveTravelDate = trip.effectiveDate,
paxTypeID = 1,
oneWayCost = Foundation.StringFormatter.currencyToDouble(tbxAirporterAdultFare.Text.Trim()),
returnCost = 0.00,
numPax = 1,
Currency = 0
};
SysVarService.SharedRideTrip_ShuttleFare cFare = new SysVarService.SharedRideTrip_ShuttleFare()
{
effectiveDate = trip.effectiveDate,
effectiveTravelDate = trip.effectiveDate,
paxTypeID = 2,
oneWayCost = Foundation.StringFormatter.currencyToDouble(tbxAirporterChildFare.Text.Trim()),
returnCost = 0.00,
numPax = 1,
Currency = 0
};
string status = "";
if (_updating)
status = Global.sysVarService.UpdateAirporterFare(trip, aFare, cFare, GetScheduleEntries());
else
status = Global.sysVarService.AddAirporterFare(trip, aFare, cFare, GetScheduleEntries());
if (!String.IsNullOrEmpty(status))
{
spanErrorMsg.Visible = true;
spanErrorMsg.InnerText = status;
return;
}
}
catch (Exception ex)
{
spanErrorMsg.Visible = true;
spanErrorMsg.InnerText = ex.ToString();
return;
}
Response.Redirect("~/Internal/Admin/Default.aspx?action=Airporter_Fares");
}
When I go to either add or update, I call GetScheduledEntries, which is supposed to loop through the datatable (grabbing it from the viewstate) and convert the templated fields into object properties and stuff these objects in a list.
private List<AdminConfigService.SharedRideTimes> GetScheduleEntries()
{
int idx = 0;
List<AdminConfigService.SharedRideTimes> schedule = new List<AdminConfigService.SharedRideTimes>();
if (gvAirporterSchedule.Rows.Count >= 1)
{
for (int i = 1; i <= gvAirporterSchedule.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
schedule.Add(new AdminConfigService.SharedRideTimes()
{
StartDate = DateTime.Parse(startDate.Text.Trim()),
EndDate = DateTime.Parse(endDate.Text.Trim()),
DepartureTime = DateTime.Parse(deptTime.Text.Trim()),
Duration = Convert.ToInt32(duration.Text.Trim()),
EffectiveDates = "",
StopID = Convert.ToInt32(ddl.SelectedValue.ToString())
});
idx++;
}
return schedule;
}
else
return schedule;
}
The problem is, if I delete rows from this grid view and then attempt to save the form, the datatable from the viewstate is bringing back those deleted rows and acting like they are still existing for saving, even though the gridview and the datatable do not have that row anymore (when the DeleteRow command goes through).
else if (e.CommandName == "DeleteRow")
{
SetRowData();
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable dt = (DataTable)ViewState["AirporterScheduleTable"];
DataRow currentRow = null;
GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int idx = gvr.RowIndex;
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[idx]);
currentRow = dt.NewRow();
ViewState["AirporterScheduleTable"] = dt;
gvAirporterSchedule.DataSource = dt;
gvAirporterSchedule.DataBind();
SetPreviousData();
}
}
}
private void SetPreviousData()
{
int idx = 0;
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable dt = (DataTable)ViewState["AirporterScheduleTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
ddl.SelectedValue = dt.Rows[i]["LocColumn"].ToString();
startDate.Text = dt.Rows[i]["StartDateColumn"].ToString();
endDate.Text = dt.Rows[i]["EndDateColumn"].ToString();
deptTime.Text = dt.Rows[i]["DeptTimeColumn"].ToString();
duration.Text = dt.Rows[i]["DurationColumn"].ToString();
idx++;
}
}
}
}
private void SetRowData()
{
int idx = 0;
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable current = (DataTable)ViewState["AirporterScheduleTable"];
DataRow currentRow = null;
if (current.Rows.Count > 0)
{
for (int i = 1; i <= current.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
currentRow = current.NewRow();
current.Rows[i - 1]["LocColumn"] = ddl.SelectedValue;
current.Rows[i - 1]["StartDateColumn"] = startDate.Text;
current.Rows[i - 1]["EndDateColumn"] = endDate.Text;
current.Rows[i - 1]["DeptTimeColumn"] = deptTime.Text;
current.Rows[i - 1]["DurationColumn"] = duration.Text;
idx++;
}
ViewState["AirporterScheduleTable"] = current;
}
}
}
There doesn't seem to be any where in the code that I am not updating the ViewState datatable when I either delete or add entries to this dynamic gridview. What could be causing the difference in ViewStates? Does the full postback of the button outside of the UpdatePanel and GridView have a different ViewState?
I also pretty much followed this tutorial exactly.
Turned out to be one of those cases where you overlook something simple. When I was populating the grid with data on load, I did not protect it with a
if (!Page.IsPostback)
Because of that, every time the row was deleted, it would refill the data table with the data on Page Load and cause the weird issues where deleted rows didn't seem to be getting deleted.

how to fill dropdown in telerik grid databound?

i have a telerik grid and use GridTemplateColumn as bellow
<telerik:GridTemplateColumn DataField="Status" ReadOnly="true" UniqueName="colStatus" HeaderText="Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="drpstatus" runat="server" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
then i fill dropdown and label in ItemDataBound event :
protected void grdList_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem editItem = (GridEditableItem)e.Item;
var info = (ProductViewInfo)e.Item.DataItem;
DropDownList drpstatus = (DropDownList)editItem["colStatus"].FindControl("drpstatus");
var cntType = new ProductTypeController();
var lst = cntType.GetStatusList(PortalId, enumTypes.MainGroup);
drpstatus.DataSource = lst;
drpstatus.DataTextField = "Caption";
drpstatus.DataValueField = "StatusID";
drpstatus.DataBind();
drpstatus.SelectedValue = info.Status.ToString();
}
else
{
var item = e.Item as GridDataItem;
var info = (ProductViewInfo)item.DataItem;
Label lblStatus = (Label)item["colStatus"].FindControl("lblStatus");
lblStatus.Text = info.StatusCaption;
}
}
}
but my drop down does not fill! "e.Item.IsInEditMode" always returns false. should i add anything else in order to fill dropdown?
I guess the problem related to ReadOnly="true"
try to remove it

trigger for a button in a gridview in update panel

I have a gridview in an update panel and it is working fine. However on the click of the edit button I want to open the edit form. But the edit button click is not working. When i debug it, the method is working fine however the page doesn't postback. I have tried using triggers but to no avail.
<asp:UpdatePanel ID="upnlgrid" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:GridView ID="gvGroupMaster" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanging="gvGroupMaster_SelectedIndexChanging" OnSelectedIndexChanged="gvGroupMaster_SelectedIndexChanged" OnRowDataBound="gvGroupMaster_RowDataBound" AllowSorting="true" OnPageIndexChanging="gvGroupMaster_PageIndexChanging" OnSorting="gvGroupMaster_Sorting"
ShowHeader="True" CssClass="tabledata" Width="100%" DataKeyNames="igroup_id">
<AlternatingRowStyle CssClass="pointer" />
<RowStyle CssClass="even pointer" />
<HeaderStyle CssClass="headings" />
<Columns>
<asp:TemplateField HeaderText="Sort Order" ItemStyle-CssClass="colmn1" SortExpression="isort_position" >
<ItemTemplate>
<%-- <asp:ImageButton ID="btnSort" OnClick="btnSortClick" imageurl="../images/order-sort-btnup.png" runat="server"></asp:ImageButton>--%>
<asp:Button ID="btnSort" class="sortord pointer" runat="server" OnClick="btnSortClick" ></asp:Button>
<asp:Button ID="btnSortDown" class="sortorddown pointer" runat="server" OnClick="btnSortDownClick"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group Name" SortExpression="strgroup_name" ItemStyle-CssClass="colmn2" >
<ItemTemplate>
<asp:Label ID="lblGroupName" runat="server"
Text='<%# Bind("strgroup_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Short Name" SortExpression="strgroup_sname" ItemStyle-CssClass="colmn3" >
<ItemTemplate>
<asp:Label ID="lblShortName" runat="server"
Text='<%# Bind("strgroup_sname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Under" SortExpression="iparent_id" ItemStyle-CssClass="colmn4">
<ItemTemplate>
<asp:Label ID="lblUnder" runat="server"
Text='<%# Bind("strunder") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nature Of Group" SortExpression="strnature_of_group" ItemStyle-CssClass="colmn5">
<ItemTemplate>
<asp:Label ID="lblNatureOfGroup" runat="server"
Text='<%# Bind("strnature_of_group") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Affect Gross Profit" SortExpression="straffect_gross_profits" ItemStyle-CssClass="colmn6">
<ItemTemplate>
<asp:Label ID="lblAffectGrossProfits" runat="server" Text='<%# Bind("straffect_gross_profits") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nett DrCr Report" SortExpression="strnett_drcr_report" ItemStyle-CssClass="colmn7">
<ItemTemplate>
<asp:Label ID="lblNettDrcrReport" runat="server"
Text='<%# Bind("strnett_drcr_report") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created By" SortExpression="icreated_by" ItemStyle-CssClass="colmn8">
<ItemTemplate>
<asp:Label ID="lblCreatedBy" runat="server"
Text='<%# Bind("strcreated_by") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created On" SortExpression="dtcreated_on" ItemStyle-CssClass="colmn9">
<ItemTemplate>
<asp:Label ID="lblCreatedOn" runat="server"
Text='<%# Bind("dtcreated_on") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Updated On" SortExpression="dtupdated_on" ItemStyle-CssClass="colmn10">
<ItemTemplate>
<asp:Label ID="lbLastUpdatedOn" runat="server"
Text='<%# Bind("dtupdated_on") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions" ItemStyle-CssClass="colmn11">
<ItemTemplate>
<asp:Button id="btnInfo" runat="server" class="infoicon" Text='<%# Eval("igroup_id") %>' OnClick="infoclick"/>
<asp:Button id="btnEdit" runat="server" class="editicon" CausesValidation="false" Text='<%# Eval("igroup_id") %>' OnClick="editclick"/>
<asp:Button id="btnDelete" runat="server" class="deleteicon" Text='<%# Eval("igroup_id") %>' OnClick="deleteclick"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
codebehind for edit click
protected void editclick(object sender, EventArgs e)
{
try
{
//int rindex = (((GridViewRow)(((Button)(sender)).Parent.BindingContainer))).RowIndex;
Button EditButton = (Button)gvGroupMaster.Rows[(((GridViewRow)(((Button)(sender)).Parent.BindingContainer))).RowIndex].FindControl("btnEdit");
edit(EditButton.Text.ToString());
this.Session["edit"] = EditButton.Text.ToString();
}
catch
{
}
}
protected void edit(string editid)
{
try
{
GroupMasterClass gm = new GroupMasterClass();
CompanyMasterClass co = new CompanyMasterClass();
gm.igroup_id = Convert.ToInt32(editid);
ResultClass objres = gm.fn_GetGroupByIdForEdit();
if (objres.bStatus)
{
eslist<GroupMasterClass> OBJLIST = objres.objData as eslist<GroupMasterClass>;
if (OBJLIST.Count > 0)
{
co.strcompany_code = Request.Cookies["userinfo"]["companycode"].ToString();
ResultClass objress = co.fn_GetNameNumberStyle();
if (objress.bStatus)
{
eslist<CompanyMasterClass> OBJLISTS = objress.objData as eslist<CompanyMasterClass>;
if (OBJLISTS.Count > 0)
{
addfrm.Visible = true;
gridmain.Visible = false;
if (OBJLISTS[0].strname_style.ToString() == "PC")
{
txtGroupName.Text = misc.ToTitleCase(OBJLIST[0].strgroup_name);
txtGroupSname.Text = misc.ToTitleCase(OBJLIST[0].strgroup_sname);
}
if (OBJLISTS[0].strname_style.ToString() == "UC")
{
txtGroupName.Text = (OBJLIST[0].strgroup_name).ToUpper();
txtGroupSname.Text = (OBJLIST[0].strgroup_sname).ToUpper();
txtGroupName.Style.Add("text-transform", "uppercase");
txtGroupSname.Style.Add("text-transform", "uppercase");
}
if (OBJLISTS[0].strname_style.ToString() == "UG")
{
txtGroupName.Text = (OBJLIST[0].strgroup_name).ToUpper();
txtGroupSname.Text = (OBJLIST[0].strgroup_sname).ToUpper();
}
}
}
txtUnder.Text = OBJLIST[0].strunder;
txtNotes.Text = OBJLIST[0].strnotes;
for (int i = 0; i < OBJLIST.Count; i++)
{
CompanyMasterClass cm = new CompanyMasterClass();
string p = OBJLIST[0].strcompany_code.ToString();
string t = string.Empty;
string code = string.Empty;
int count = 0;
string[] availcompanycode = p.Split(',');
foreach (string k in availcompanycode)
{
t = k.ToString();
code += "'" + t.ToString() + "'" + ",";
count++;
}
cm.strcompany_code = code.TrimEnd(',');
ResultClass objrest = cm.fn_GetCompanyListByCompanycode();
if (objres.bStatus)
{
eslist<CompanyMasterClass> OBJLISTS = objrest.objData as eslist<CompanyMasterClass>;
if (OBJLISTS.Count > 0)
{
// listboxsource.Items.Clear();
listboxdestination.DataTextField = "strcompany_name";
listboxdestination.DataValueField = "strcompany_code";
listboxdestination.DataSource = OBJLISTS;
listboxdestination.DataBind();
}
}
ListItem itemnature = new ListItem();
if (OBJLIST[i].strnature_of_group == "A")
itemnature.Text = "Assets";
else if (OBJLIST[i].strnature_of_group == "E")
itemnature.Text = "Expenses";
else if (OBJLIST[i].strnature_of_group == "I")
itemnature.Text = "Income";
else if (OBJLIST[i].strnature_of_group == "L")
itemnature.Text = "Liabilities";
// itemnature.Value = OBJLIST[i].igroup_id.ToString();
ddlNature.Items.Add(itemnature);
ListItem itemaffects = new ListItem();
if (OBJLIST[i].straffect_gross_profits == "N")
itemaffects.Text = "No";
else if (OBJLIST[i].straffect_gross_profits == "Y")
itemaffects.Text = "Yes";
//itemaffects.Value = OBJLIST[i].igroup_id.ToString();
ddlGrossProfit.Items.Add(itemaffects);
ListItem itemnett = new ListItem();
if (OBJLIST[i].strnett_drcr_report == "N")
itemnett.Text = "No";
else if (OBJLIST[i].strnett_drcr_report == "Y")
itemnett.Text = "Yes";
// itemnett.Value = OBJLIST[i].igroup_id.ToString();
ddlNett.Items.Add(itemnett);
ListItem itemlock = new ListItem();
if (OBJLIST[i].strlock_status == "N")
itemlock.Text = "No";
else if (OBJLIST[i].strlock_status == "Y")
itemlock.Text = "Yes";
// itemnett.Value = OBJLIST[i].igroup_id.ToString();
ddlNett.Items.Add(itemlock);
}
}
}
}
catch
{
}
}
Any ideas?
Thanks,
Try using Button editbtn = (Button)sender; Rather than Button EditButton = (Button)gvGroupMaster.Rows[(((GridViewRow)(((Button)(sender)).Parent.BindingContainer))).RowIndex].FindControl("btnEdit");

Categories