I am having problems trying to get a rowcommand event to fire in a gridview. I followed the code example from MSDNet but I cannot figure out why it is not working. The code is below. Thank you.
<asp:GridView ID="GridViewProducts" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="5" CellSpacing="1" DataKeyNames="Pkey"
DataSourceID="SqlDataSourceProducts" ForeColor="Black" GridLines="Vertical">
<FooterStyle BackColor="#CCCCCC" />
<PagerSettings PageButtonCount="20" />
<Columns>
<asp:BoundField DataField="Product" HeaderText="Product" >
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField HeaderText="Interest">
<ItemTemplate>
<asp:DropDownList ID="ddlProductInterest" runat="server" SelectedValue='<%# Bind("ProductInterest") %>'>
<asp:ListItem></asp:ListItem>
<asp:ListItem>Low</asp:ListItem>
<asp:ListItem>Medium</asp:ListItem>
<asp:ListItem>High</asp:ListItem>
<asp:ListItem>None</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button runat="server" ID="TestButton" Text="Button" CommandName="Test"
CommandArgument="<%# CType(Container, GridViewRow).RowIndex %>" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="center" />
<ItemStyle HorizontalAlign="center" />
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Silver" Font-Bold="True" ForeColor="Black" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
++Code Behind +++
Sub GridViewProducts_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName = "Test" Then
Dim index = Convert.ToInt32(e.CommandArgument)
Dim row = GridViewProducts.Rows(index)
Dim MyString As String = row.Cells(0).Text
strSQL = "INSERT INTO tblClosedProducts (" & _
"Product, ClosedBy, DateClosed " & _
") VALUES (" & _
"#Product, #ClosedBy, #DateClosed " & _
")"
Dim MyParameters1 As SqlParameter() = { _
New SqlParameter("#Product", SqlDbType.VarChar), _
New SqlParameter("#ClosedBy", SqlDbType.VarChar), _
New SqlParameter("#DateClosed", SqlDbType.SmallDateTime) _
}
MyParameters1(0).Value = row.Cells(0).Text
MyParameters1(1).Value = GetInfo.GetFullName(UCase(Right(HttpContext.Current.User.Identity.Name.ToString(), 4)))
MyParameters1(2).Value = DateAdd("h", -1, Now())
objData.SQLExecuteNonQuery(strSQL, CommandType.Text, MyParameters1)
End If
End Sub
Your gridview doesnt have the event wired up in its markup.
Try adding in onrowcommand="GridViewProducts_RowCommand" so it looks like this:
<asp:GridView ID="GridViewProducts" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="5" CellSpacing="1" DataKeyNames="Pkey"
DataSourceID="SqlDataSourceProducts" ForeColor="Black" GridLines="Vertical"
onrowcommand="GridViewProducts_RowCommand">
#rtpHarry is correct, and that is a valid way to wire up the event. Another method of wiring the event would be to change the signature of your method in the code behind to add Handles Me.GridViewProducts.RowCommand to the end:
Sub GridViewProducts_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles Me.GridViewProducts.RowCommand
protected void Add_Update_Remove_Row(int Index, string Operation)
{
//DataTable dt = (DataTable)ViewState["Table_BinaryPayment"];
int ID = Index;
Label lblddt = (Label)GridView1.Rows[Index].FindControl("Label2");
Label lblttm = (Label)GridView1.Rows[Index].FindControl("Label1");
Label lblid = (Label)GridView1.Rows[Index].FindControl("lblID");
Label lblaeamt = (Label)GridView1.Rows[Index].FindControl("lblamt");
Label lblprojID = (Label)GridView1.Rows[Index].FindControl("lblprojectID");
Label lblpaydetails = (Label)GridView1.Rows[Index].FindControl("lblpaydetails");
Label lblexpdate = (Label)GridView1.Rows[Index].FindControl("lblExpDate");
Label lblexpttime = (Label)GridView1.Rows[Index].FindControl("lblExpTime");
Label lblalloycodes = (Label)GridView1.Rows[Index].FindControl("lblalloycode");
Label lblalloyrates = (Label)GridView1.Rows[Index].FindControl("lblalloyRate");
Label lbladddelivered = (Label)GridView1.Rows[Index].FindControl("lbladdtodeliver");
Label lblEID = (Label)GridView1.Rows[Index].FindControl("lblEID");
ViewState["DispTime"] = lblttm.Text;
ViewState["ExpTime"] = lblexpttime.Text;
if (Operation == "Modify")
{
//lblchqNo.Text = txtchequeNO1.Text;
//lblchqDate.Text = txtchequeDate1.Text;
//lblAccountNo.Text = txtAccountNo.Text;
//lblBName.Text = txtBankName.Text;
lblddt.Text = txtdispdate.Text;
if (ddldisphr.SelectedItem.Text == "00" & ddldispmin.SelectedItem.Text == "00" & ddldispsec.SelectedItem.Text == "00")
{
lblttm.Text = ViewState["DispTime"].ToString();
}
else
{
lblttm.Text = (ddldisphr.SelectedItem.Text + ":" + ddldispmin.SelectedItem.Text + ":" + ddldispsec.SelectedItem.Text);
}
if (ddlexphr.SelectedItem.Text == "00" & ddlexpmin.Text == "00" & ddlexpsec.Text == "00")
{
lblexpttime.Text = ViewState["ExpTime"].ToString();
}
else
{
lblexpttime.Text = (ddlexphr.SelectedItem.Text + ":" + ddlexpmin.Text + ":" + ddlexpsec.Text);
}
lblaeamt.Text = txtadvPayment.Text;
lblpaydetails.Text = txtpaymentdetails.Text;
lblexpdate.Text = txtexpdate.Text;
lblalloycodes.Text = ddlalloycode.SelectedItem.Text;
lblalloyrates.Text = txtalloyrate.Text;
lbladddelivered.Text = txtaadtodel.Text;
//ExecuteProcedures ex = new ExecuteProcedures(4);
//string proc="Inse_Clientorder";
//ex.Parameters.Add("#dtPayment_Date", SqlDbType.DateTime, lblddt.Text);
//ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, lblttm.Text);
//ex.Parameters.Add("#Enquiry_ID", SqlDbType.VarChar, ID );
//ex.Parameters.Add("#numAdvance_Amount", SqlDbType.Float , Convert.ToDouble(txtadvPayment.Text ));
//bool s = ex.InvokeProcedure(proc);
ExecuteProcedures ex = new ExecuteProcedures(12);
//string proc = "Inse_Clientorder123";
string proc = "Inse_Clientorder321";
ex.Parameters.Add("#dtPayment_Date", SqlDbType.DateTime, Convert.ToDateTime(lblddt.Text));
//if (ddldisphr.SelectedItem.Text == "00" & ddldispmin.SelectedItem.Text == "00" & ddldispsec.SelectedItem.Text == "00")
//{
// ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, ViewState["DispTime"]);
//}
//else
//{
// ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, lblttm.Text);
//}
//if (ddlexphr.SelectedItem.Text == "00" & ddlexpmin.Text == "00" & ddlexpsec.Text == "00")
//{
// ex.Parameters.Add("#ExpTime", SqlDbType.VarChar, ViewState["ExpTime"]);
//}
//else
//{
// ex.Parameters.Add("#ExpTime", SqlDbType.VarChar, lblexpttime.Text);
//}
ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, lblttm.Text);
ex.Parameters.Add("#ExpTime", SqlDbType.VarChar, lblexpttime.Text);
ex.Parameters.Add("#Advance_Payment_ID", SqlDbType.Int, Convert.ToInt32(lblid.Text));
ex.Parameters.Add("#numAdvance_Amount", SqlDbType.VarChar, lblaeamt.Text);
ex.Parameters.Add("#AlooyCode", SqlDbType.VarChar, lblalloycodes.Text);
ex.Parameters.Add("#numRate", SqlDbType.Float, Convert.ToDouble(lblalloyrates.Text));
ex.Parameters.Add("#vcrDescription", SqlDbType.VarChar, lbladddelivered.Text);
ex.Parameters.Add("#Client_Ordered_Projects_ID", SqlDbType.Int, Convert.ToInt32(lblprojID.Text));
ex.Parameters.Add("#Enquiry_ID", SqlDbType.Int, Convert.ToInt32(lblEID.Text));
ex.Parameters.Add("#dtExpectedPayment_Date", SqlDbType.DateTime, Convert.ToDateTime(lblexpdate.Text));
ex.Parameters.Add("#vcrPayment_Details", SqlDbType.VarChar, lblpaydetails.Text);
bool s = ex.InvokeProcedure(proc);
if (s == true)
{
CommonFunctions.Alert("Records Updated Successfully", this.Page);
}
else
{
CommonFunctions.Alert("Error In Updation", this.Page);
}
clear();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//if (e.CommandName == "Modify")
//{
// string strID = e.CommandArgument.ToString();
// strID = CommonFunctions.Encrypt(strID);
// Response.Redirect("Client_Order.aspx?Project_ID=" + strID);
//}
if (e.CommandName == "Modify")
{
string strID = e.CommandArgument.ToString();
int intRowIndex = ((GridViewRow)((LinkButton)e.CommandSource).Parent.Parent).RowIndex;
//Session[rowindex] = intRowIndex;
txtdispdate.Text = GridView1.Rows[intRowIndex].Cells[6].Text;
string strdisp = ((ddldisphr.SelectedItem.Text) + ":" + (ddldispmin.SelectedItem.Text) + ":" + (ddldispsec.SelectedItem.Text)).ToString();
lbltime.Text = GridView1.Rows[intRowIndex].Cells[7].Text;
Label lblClienorderiid = (Label)GridView1.Rows[intRowIndex].FindControl("lblcLOID");
Label lbledate = (Label)GridView1.Rows[intRowIndex].FindControl("Label2");
Label lbletime = (Label)GridView1.Rows[intRowIndex].FindControl("Label1");
Label lbliid = (Label)GridView1.Rows[intRowIndex].FindControl("lblID");
Label lblaamt = (Label)GridView1.Rows[intRowIndex].FindControl("lblamt");
Label lblEID = (Label)GridView1.Rows[intRowIndex].FindControl("lblEID");
Label lblprojID = (Label)GridView1.Rows[intRowIndex].FindControl("lblprojectID");
Label lblpaydetails = (Label)GridView1.Rows[intRowIndex].FindControl("lblpaydetails");
Label lblexpdate = (Label)GridView1.Rows[intRowIndex].FindControl("lblExpDate");
Label lblexpttime = (Label)GridView1.Rows[intRowIndex].FindControl("lblExpTime");
Label lblalloycodes = (Label)GridView1.Rows[intRowIndex].FindControl("lblalloycode");
Label lblalloyrates = (Label)GridView1.Rows[intRowIndex].FindControl("lblalloyRate");
Label lbladddelivered = (Label)GridView1.Rows[intRowIndex].FindControl("lbladdtodeliver");
ViewState["Index"] = intRowIndex;
ViewState["CommandName"] = e.CommandName;
txtdispdate.Text = lbledate.Text;
lbltime.Text = lbletime.Text;
txtadvPayment.Text = lblaamt.Text;
ddlalloycode.SelectedItem.Text = lblalloycodes.Text;
txtalloyrate.Text = lblalloyrates.Text;
txtaadtodel.Text = lbladddelivered.Text;
txtpaymentdetails.Text = lblpaydetails.Text;
txtexpdate.Text = lblexpdate.Text;
lblexptimess.Text = lblexpttime.Text;
pnl2.Visible = true;
//lbltime.Text = lbltm.Text;
//Add_Update_Remove_Row( intRowIndex , e.CommandName);
}
else if (e.CommandName == "Del")
{
string strID = e.CommandArgument.ToString();
string strSql = "Delete from Client_Order where Client_ID = " + strID;
string str_query = "Update Enquiry set OrderExecuted='No' where Enquiry_ID = " + strID;
//string str_query = "delete from Enquiry where Enquiry_ID = " + strID;
Dentry de = new Dentry();
de.RunCommand(strSql);
de.RunCommand(str_query);
Bind_Data();
}
else if(e.CommandName =="Invoice")
{
string strID = e.CommandArgument.ToString();
strID = CommonFunctions.Encrypt(strID);
string strType = CommonFunctions.Encrypt("New");
Response.Redirect("New_Order_Project_Invoice_Entry.aspx?Project_ID=" + strID + "&Type=" + strType);
}
else if (e.CommandName == "Delivered")
{
string strId = e.CommandArgument.ToString();
string str_query = "Update Enquiry set vcrDelivered='Yes' where Enquiry_ID=" + strId;
Dentry de = new Dentry();
de.RunCommand(str_query);
Bind_Data();
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex > -1)
{
LinkButton lnk = (LinkButton)e.Row.FindControl("lnkDelete");
lnk.Attributes.Add("onClick", "return confirm('Are you sure to delete this record?');");
}
}
Enable View State= true will solve your problem
Related
Actually I'm using GridView for fixed and percentage based commission and I'm hiding same on selected index change of radio button.
On page load I'm showing only delete option at latest row only which work properly. The problem comes when I'm trying to change the selected Index of the commission based radio button and at the same time binding data to the GridView from database accordingly.
public void LoadGrid(){
try {
DataTable DtLoadAgentCommission = new DataTable();
DtLoadAgentCommission.Columns.Add("RowNumber");
DtLoadAgentCommission.Columns.Add("MinCount");
DtLoadAgentCommission.Columns.Add("MaxCount");
DtLoadAgentCommission.Columns.Add("AgentWiseCommission");
DtLoadAgentCommission.Columns.Add("FixedAmount");
DtLoadAgentCommission.Columns.Add("CommissionType");
DtLoadAgentCommission.Columns.Add("CommissionDescription");
DataRow dr = DtLoadAgentCommission.NewRow();
dr["RowNumber"] = "1";
dr["MinCount"] = string.Empty;
dr["MaxCount"] = string.Empty;
dr["CommissionType"] = string.Empty;
dr["AgentWiseCommission"] = string.Empty;
dr["FixedAmount"] = string.Empty;
dr["CommissionDescription"] = string.Empty;
DtLoadAgentCommission.Rows.Add(dr);
grvViewFixedAgentCommisionConfiguration.DataSource = DtLoadAgentCommission;
grvViewFixedAgentCommisionConfiguration.DataBind();
ViewState["ViewAgentCommission"] = DtLoadAgentCommission;
} catch (Exception Ex) {
_clsCommandFunctions.writeLog("Exception Occured :\n ." + Ex.Message);
}
}
protected void grvViewFixedAgentCommisionConfiguration_RowDataBound(object sender, GridViewRowEventArgs e) {
try {
if (e.Row.RowType == DataControlRowType.DataRow) {
RowIndexFromGV = RowIndexFromGV + 1;
TextBox txtFixedAmountTabMinCount = (TextBox) e.Row.FindControl("txtFixedAmountTabMinCount");
TextBox txtMaxCount = (TextBox) e.Row.FindControl("txtMaxCount");
DropDownList ddlCommissionType = (DropDownList) e.Row.FindControl("ddlCommissionType");
TextBox txtInterest = (TextBox) e.Row.FindControl("txtInterest");
TextBox txtFixedAmount = (TextBox) e.Row.FindControl("txtFixedAmount");
Label lblcommissiontypeID = (Label) e.Row.FindControl("lblcommissiontypeID");
LinkButton btnRemoveAgentCommission = (LinkButton) e.Row.FindControl("btnRemoveAgentCommission");
string checkpostrowindex = e.Row.RowIndex.ToString();
if (!string.IsNullOrEmpty(hdfremovecommIDs.Value)) {
int removedId = Convert.ToInt32(hdfremovecommIDs.Value) - 1;
if (removedId.ToString().Equals(checkpostrowindex)) {
btnRemoveAgentCommission.Visible = true;
}
} else
if (RowsCountFromGV == RowIndexFromGV) {
btnRemoveAgentCommission.Visible = true;
}
if (rbtnFixedAmountTab1.SelectedValue == "1") {
grvViewFixedAgentCommisionConfiguration.Columns[4].Visible = false;
grvViewFixedAgentCommisionConfiguration.Columns[5].Visible = true;
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alert", string.Format("alert('Commission slab can be change only on 1st Date of month.')"), true);
} else {
grvViewFixedAgentCommisionConfiguration.Columns[4].Visible = true;
grvViewFixedAgentCommisionConfiguration.Columns[5].Visible = false;
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alert", string.Format("alert('Commission slab can be change only on 1st Date of month.')"), true);
}
} catch (Exception Ex) {
_clsCommandFunctions.writeLog("Exception Occured :\n ." + Ex.Message);
}
}
}
protected void rbtnFixedAmountTab1_SelectedIndexChanged(object sender, EventArgs e) {
try {
if (DateTime.Now.ToString("dd") == Convert.ToString(ConfigurationManager.AppSettings["StartOfDate"])) {
fillAgentCommisionData();
if (rbtnFixedAmountTab1.SelectedValue.Equals("1")) {
grvViewFixedAgentCommisionConfiguration.Columns[4].Visible = false;
grvViewFixedAgentCommisionConfiguration.Columns[5].Visible = true;
} else if (rbtnFixedAmountTab1.SelectedValue.Equals("2")) {
grvViewFixedAgentCommisionConfiguration.Columns[4].Visible = true;
grvViewFixedAgentCommisionConfiguration.Columns[5].Visible = false;
}
} else {
if (rbtnFixedAmountTab1.SelectedIndex == 1) {
} else {
}
string DateValue = Convert.ToString(ConfigurationManager.AppSettings["StartOfDate"]);
Response.Write("<script language='javascript'>window.alert('Commission type can be change only on " + DateValue + " Date of month. " + "');</script>");
} catch (Exception ex) {
AppLog.ErrorLog(sender, ex);
ScriptManager.RegisterStartupScript(this.Page, typeof(string), "msg", "alert('Alarm: Contact system administrator');", true);
}
}
}
public void fillAgentCommisionData() {
try {
DataTable AgentCommisionConfiguration = new DataTable();
AgentCommisionConfiguration = MobilePortalProcess.GetAgentCommisionConfigurationDetails();
if (AgentCommisionConfiguration.Rows.Count > 0) {
if (rbtnFixedAmountTab1.SelectedValue.Equals("0") || rbtnFixedAmountTab1.SelectedValue.Equals("1") || rbtnFixedAmountTab1.SelectedValue.Equals("2")) {
} else {
RowsCountFromGV = AgentCommisionConfiguration.Rows.Count;
rbtnFixedAmountTab1.Items.FindByText(AgentCommisionConfiguration.Rows[0]["CommissionDescription"].ToString()).Selected = true;
}
grvViewFixedAgentCommisionConfiguration.DataSource = AgentCommisionConfiguration;
grvViewFixedAgentCommisionConfiguration.DataBind();
AgentCommissionType = AgentCommisionConfiguration.Rows[0]["CommissionDescription"].ToString();
ViewState["ViewAgentCommission"] = AgentCommisionConfiguration;
}
} catch (Exception Ex) {
_clsCommandFunctions.writeLog("Exception Occured :\n ." + Ex.Message);
}
}
private void SetPreviousAgentCommission() {
try {
int rowIndex = 0;
if (ViewState["ViewAgentCommission"] != null) {
DataTable dt = (DataTable) ViewState["ViewAgentCommission"];
if (dt.Rows.Count > 0) {
for (int i = 0; i < dt.Rows.Count; i++) {
Label RowNumber = (Label) grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[1].FindControl("RowNumber");
TextBox txtFixedAmountTabMinCount = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[1].FindControl("txtFixedAmountTabMinCount");
TextBox txtMaxCount = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[2].FindControl("txtMaxCount");
DropDownList ddlCommissionType = (DropDownList) grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[3].FindControl("ddlCommissionType");
TextBox txtInterest = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[4].FindControl("txtInterest");
TextBox txtFixedAmount = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[5].FindControl("txtFixedAmount");
RowNumber.Text = Convert.ToString(rowIndex + 1);
txtFixedAmountTabMinCount.Text = dt.Rows[i]["MinCount"].ToString();
txtMaxCount.Text = dt.Rows[i]["MaxCount"].ToString();
ddlCommissionType.SelectedValue = dt.Rows[i]["CommissionType"].ToString();
txtInterest.Text = dt.Rows[i]["AgentWiseCommission"].ToString();
txtFixedAmount.Text = dt.Rows[i]["FixedAmount"].ToString();
rowIndex++;
}
}
}
} catch (Exception Ex) {
_clsCommandFunctions.writeLog("Exception Occured :\n ." + Ex.Message);
}
}
protected void grvViewFixedAgentCommisionConfiguration_RowCommand(object sender, GridViewCommandEventArgs e) {
try {
string _CommandName = Convert.ToString(e.CommandName);
if (_CommandName == "AddCommssionDetails") {
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Confirm()", true);
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes") {
// if (DateTime.Now.ToString("dd") == new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("dd"))
if (DateTime.Now.ToString("dd") == Convert.ToString(ConfigurationManager.AppSettings["StartOfDate"])) {
int rowindex = 0;
if (ViewState["ViewAgentCommission"] != null) {
DataTable dtAgentComission = (DataTable) ViewState["ViewAgentCommission"];
DataRow drCurrentRow = null;
if (grvViewFixedAgentCommisionConfiguration.Rows.Count > 0) {
for (int i = 1; i <= grvViewFixedAgentCommisionConfiguration.Rows.Count; i++) {
Label RowNumber = (Label) grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[1].FindControl("RowNumber");
TextBox txtFixedAmountTabMinCount = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[1].FindControl("txtFixedAmountTabMinCount");
TextBox txtMaxCount = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[2].FindControl("txtMaxCount");
DropDownList ddlCommissionType = (DropDownList) grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[3].FindControl("ddlCommissionType");
TextBox txtInterest = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[4].FindControl("txtInterest");
TextBox txtFixedAmount = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[5].FindControl("txtFixedAmount");
Label lblCommissionType = (Label) grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[6].FindControl("lblCommissionType");
Label lblCommissionTypeName = (Label) grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[7].FindControl("lblCommissionTypeName");
drCurrentRow = dtAgentComission.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtAgentComission.Rows[i - 1]["MinCount"] = txtFixedAmountTabMinCount.Text;
dtAgentComission.Rows[i - 1]["MaxCount"] = txtMaxCount.Text;
dtAgentComission.Rows[i - 1]["CommissionType"] = ddlCommissionType.SelectedValue.ToString();
dtAgentComission.Rows[i - 1]["AgentWiseCommission"] = txtInterest.Text;
dtAgentComission.Rows[i - 1]["FixedAmount"] = txtFixedAmount.Text;
dtAgentComission.Rows[i - 1]["CommissionType"] = lblCommissionType.Text;
dtAgentComission.Rows[i - 1]["CommissionDescription"] = lblCommissionTypeName.Text;
rowindex++;
}
dtAgentComission.Rows.Add(drCurrentRow);
ViewState["ViewAgentCommission"] = dtAgentComission;
grvViewFixedAgentCommisionConfiguration.DataSource = dtAgentComission;
grvViewFixedAgentCommisionConfiguration.DataBind();
}
SetPreviousAgentCommission();
}
} else {
string DateValue = Convert.ToString(ConfigurationManager.AppSettings["StartOfDate"]);
Response.Write("<script language='javascript'>window.alert('Commission slab can be change only on " + DateValue + " Date of month. " + "');</script>");
}
} else {
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alert", string.Format("alert('You clicked Cancel.')"), true);
}
}
if (_CommandName == "RemoveAgentCommission") {
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "ConfirmOnCancel()", true);
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes") {
DataTable dtRemoveAgentComission = (DataTable) ViewState["ViewAgentCommission"];
DataRow drCurrentRow = null;
LinkButton lnkBtn = (LinkButton) e.CommandSource;
GridViewRow myRow = (GridViewRow) lnkBtn.Parent.Parent;
int rowindex = myRow.RowIndex;
hdfremovecommIDs.Value = rowindex.ToString();
int rowIndex1 = 0;
if (dtRemoveAgentComission.Rows.Count > 1) {
for (int i = 1; i <= grvViewFixedAgentCommisionConfiguration.Rows.Count; i++) {
Label RowNumber = (Label) grvViewFixedAgentCommisionConfiguration.Rows[rowIndex1].Cells[1].FindControl("RowNumber");
TextBox txtFixedAmountTabMinCount = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowIndex1].Cells[1].FindControl("txtFixedAmountTabMinCount");
TextBox txtMaxCount = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowIndex1].Cells[2].FindControl("txtMaxCount");
DropDownList ddlCommissionType = (DropDownList) grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[3].FindControl("ddlCommissionType");
TextBox txtInterest = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowIndex1].Cells[4].FindControl("txtInterest");
TextBox txtFixedAmount = (TextBox) grvViewFixedAgentCommisionConfiguration.Rows[rowIndex1].Cells[5].FindControl("txtFixedAmount");
Label lblCommissionType = (Label) grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[6].FindControl("lblCommissionType");
Label lblCommissionTypeName = (Label) grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[7].FindControl("lblCommissionTypeName");
drCurrentRow = dtRemoveAgentComission.NewRow();
dtRemoveAgentComission.Rows[i - 1]["MinCount"] = txtFixedAmountTabMinCount.Text;
dtRemoveAgentComission.Rows[i - 1]["MaxCount"] = txtMaxCount.Text;
dtRemoveAgentComission.Rows[i - 1]["CommissionType"] = ddlCommissionType.SelectedValue.ToString();
dtRemoveAgentComission.Rows[i - 1]["AgentWiseCommission"] = txtInterest.Text;
dtRemoveAgentComission.Rows[i - 1]["FixedAmount"] = txtFixedAmount.Text;
dtRemoveAgentComission.Rows[i - 1]["CommissionType"] = lblCommissionType.Text;
dtRemoveAgentComission.Rows[i - 1]["CommissionDescription"] = lblCommissionTypeName.Text;
rowIndex1++;
}
// dtRemoveAgentComission.Rows.Add(drCurrentRow);
dtRemoveAgentComission.Rows.Remove(dtRemoveAgentComission.Rows[rowindex]);
ViewState["VW_gvAgentcommission"] = dtRemoveAgentComission;
//RowsCountFromGV = dtRemoveAgentComission.Rows.Count;
// RowIndexFromGV = dtRemoveAgentComission.Rows.Count;
grvViewFixedAgentCommisionConfiguration.DataSource = dtRemoveAgentComission;
grvViewFixedAgentCommisionConfiguration.DataBind();
}
} else {
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alert", string.Format("alert('You clicked Cancel.')"), true);
}
}
} catch (Exception Ex) {
_clsCommandFunctions.writeLog("Exception Occured :\n ." + Ex.Message);
}
}
ASPX design shown below:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:GridView ID="grvViewFixedAgentCommisionConfiguration" runat="server" DataKeyNames="RowNumber" EmptyDataText="No Data Found" ShowFooter="true" class="display table-responsive" Style="border: 1px solid rgb(221, 221, 221); width: 100%;" CellPadding="0" CellSpacing="0" border="0" EnableModelValidation="True" OnRowDataBound="grvViewFixedAgentCommisionConfiguration_RowDataBound" AutoGenerateColumns="false" OnRowCommand="grvViewFixedAgentCommisionConfiguration_RowCommand">
<%--OnRowCreated="grvViewFixedAgentCommisionConfiguration_RowCreated"--%>
<Columns>
<asp:TemplateField HeaderText="Sl.No.">
<ItemTemplate>
<asp:Label ID="RowNumber" CssClass="control-label" runat="server" Text='<%#Container.DataItemIndex+1%>'></asp:Label>
</ItemTemplate>
<ItemStyle Wrap="false" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Min Count">
<ItemTemplate>
<asp:TextBox ID="txtFixedAmountTabMinCount" runat="server" MaxLength="33" PlaceHolder="Enter Minimum Count" CssClass="form-control" Width="100%" Text='<%#Eval("MinCount") %>'></asp:TextBox>
<cc1:FilteredTextBoxExtender ID="txtInterest_FilteredtxtFixedAmountTabMinCount" runat="server" Enabled="True" TargetControlID="txtFixedAmountTabMinCount" FilterType="Numbers,Custom" FilterMode="ValidChars" ValidChars=" .">
</cc1:FilteredTextBoxExtender>
</ItemTemplate>
<ItemStyle Wrap="false" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Max Count">
<ItemTemplate>
<asp:TextBox ID="txtMaxCount" MaxLength="13" PlaceHolder="Enter Maximum Count" runat="server" CssClass="form-control" Text='<%#Eval("MaxCount") %>'></asp:TextBox>
<cc1:FilteredTextBoxExtender ID="txtInterest_FilteredtxtMaxCount" runat="server" Enabled="True" TargetControlID="txtMaxCount" FilterType="Numbers,Custom" FilterMode="ValidChars" ValidChars=" .">
</cc1:FilteredTextBoxExtender>
</ItemTemplate>
<ItemStyle Wrap="false" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Commssion Type" Visible="false">
<ItemTemplate>
<asp:Label ID="lblcommissiontypeID" runat="server" Text='<%#Eval("CommissionType") %>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddlCommissionType" runat="server" CssClass="form-control" OnSelectedIndexChanged="ddlCommissionType_SelectedIndexChanged" Width="100%" AutoPostBack="true">
<asp:ListItem Value="0" Text="--Select--"></asp:ListItem>
<asp:ListItem Value="1" Text="Fixed Amount"> </asp:ListItem>
<asp:ListItem Value="2" Text="Percentage Wise"> </asp:ListItem>
</asp:DropDownList>
</div>
</ItemTemplate>
<ItemStyle Wrap="false" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Interest">
<ItemTemplate>
<asp:TextBox ID="txtInterest" MaxLength="13" PlaceHolder="Enter Interest Rate" runat="server" CssClass="form-control" Text='<%#Eval("AgentWiseCommission") %>'></asp:TextBox>
<cc1:FilteredTextBoxExtender ID="txtInterest_FilteredTextBoxExtender" runat="server" Enabled="True" TargetControlID="txtInterest" FilterType="Numbers,Custom" FilterMode="ValidChars" ValidChars=" .">
</cc1:FilteredTextBoxExtender>
</ItemTemplate>
<ItemStyle Width="25%" Wrap="false" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Global Amount">
<ItemTemplate>
<asp:TextBox ID="txtFixedAmount" MaxLength="13" PlaceHolder="Enter Fixed Amount" runat="server" CssClass="form-control" Width="94%" Text='<%#Eval("FixedAmount") %>'></asp:TextBox>
<cc1:FilteredTextBoxExtender ID="txtInterest_FilteredtxtFixedAmount" runat="server" Enabled="True" TargetControlID="txtFixedAmount" FilterType="Numbers,Custom" FilterMode="ValidChars" ValidChars=" .">
</cc1:FilteredTextBoxExtender>
</ItemTemplate>
<ItemStyle Width="25%" Wrap="false" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Commision Type" Visible="false">
<ItemTemplate>
<asp:Label ID="lblCommissionType" runat="server" Text='<%#Eval("CommissionType")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Commision Type Name" Visible="false">
<ItemTemplate>
<asp:Label ID="lblCommissionTypeName" runat="server" Text='<%#Eval("CommissionDescription")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="btnRemoveAgentCommission" runat="server" CommandName="RemoveAgentCommission" OnClientClick="ConfirmOnCancel()" CommandArgument='<%#Eval("RowNumber") %>' Visible="false">
<asp:Image ImageUrl="../Images/minus.png" ID="imgRemoveTeamEmployee" runat="server" ToolTip="Click to delete this row" Style="cursor: pointer;" rel="tooltip" data-original-title="RemoveTeamEmployeeSubTask" class="tableActionButton" />
</asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="4%" Wrap="false" />
<FooterTemplate>
<asp:LinkButton ID="btnAddSubTask" runat="server" CommandName="AddCommssionDetails" OnClientClick="Confirm()" CommandArgument='<%#Eval("RowNumber") %>'>
<asp:Image ImageUrl="../Images/plus.png" ID="imgAddEmp" runat="server" ToolTip="Click to add new Row" Style="cursor: pointer;" rel="tooltip" data-original-title="AddSubTask" class="tableActionButton" />
</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Content>
ClassFiles.clsCommandFunctions _clsCommandFunctions = new ClassFiles.clsCommandFunctions();
DataTable GetCommissionAgent = null;
string AgentCode = string.Empty;
string CommisionType = string.Empty;
string ViewCommisionType = string.Empty;
string CommisionMinCount1 = string.Empty;
string CommisionMaxCount1 = string.Empty;
string CommisionAmount1 = string.Empty;
string CommisionPercentage1 = string.Empty;
string CommisionMinCount2 = string.Empty;
string CommisionMaxCount2 = string.Empty;
string CommisionAmount2 = string.Empty;
string CommisionPercentage2 = string.Empty;
string CommisionMinCount3 = string.Empty;
string CommisionMaxCount3 = string.Empty;
string CommisionAmount3 = string.Empty;
string CommisionPercentage3 = string.Empty;
DataTable InsertOrUpdateAgentCommission = null;
DataTable FixedUpdateAgentCommission = null;
DataTable RemoveAgentWiseCommission = null;
DataSet ViewAgentCommissionData = new DataSet();
string NewAgentcode = string.Empty;
string ViewAgentCode = string.Empty;
string EditAgentCode = string.Empty;
string Type = string.Empty;
int Status = -1;
// start of Initialization of variable for maintaining adding and removing row index
int RowsCountFromGV = 0;
int RowIndexFromGV = -1;
// End of Initialization of variable for maintaining adding and removing row index
DataTable GetViewCommissionDetails = null;
DataSet ViewAgentData = new DataSet();
DataTable InsertUpdateAgentCommission = null;
string CommissionDescription = string.Empty;
if (!IsPostBack)
{
if (Session["Username"] != null)
{
LoadGrid();
fillAgentCommisionData();
}
else
{
Response.Redirect("~/frmLogin.aspx");
}
}
enter code here
public void LoadGrid()
{
try
{
DataTable DtLoadAgentCommission = new DataTable();
DtLoadAgentCommission.Columns.Add("RowNumber");
DtLoadAgentCommission.Columns.Add("MinCount");
DtLoadAgentCommission.Columns.Add("MaxCount");
DtLoadAgentCommission.Columns.Add("AgentWiseCommission");
DtLoadAgentCommission.Columns.Add("FixedAmount");
DtLoadAgentCommission.Columns.Add("CommissionType");
DtLoadAgentCommission.Columns.Add("CommissionDescription");
DataRow dr = DtLoadAgentCommission.NewRow();
dr["RowNumber"] = "1";
dr["MinCount"] = string.Empty;
dr["MaxCount"] = string.Empty;
dr["CommissionType"] = string.Empty;
dr["AgentWiseCommission"] = string.Empty;
dr["FixedAmount"] = string.Empty;
dr["CommissionDescription"] = string.Empty;
DtLoadAgentCommission.Rows.Add(dr);
grvViewFixedAgentCommisionConfiguration.DataSource = DtLoadAgentCommission;
grvViewFixedAgentCommisionConfiguration.DataBind();
ViewState["ViewAgentCommission"] = DtLoadAgentCommission;
}
catch (Exception Ex)
{
_clsCommandFunctions.writeLog("Exception Occurred :\n ." + Ex.Message);
}
}
enter code here
public void fillAgentCommisionData()
{
try
{
DataTable AgentCommisionConfiguration = new DataTable();
AgentCommisionConfiguration = MobilePortalProcess.GetAgentCommisionConfigurationDetails();
RowsCountFromGV = AgentCommisionConfiguration.Rows.Count; // To store total count of records for showing remove row option
if (AgentCommisionConfiguration.Rows.Count > 0)
{
if (rbtnFixedAmountTab1.SelectedValue.Equals("0") || rbtnFixedAmountTab1.SelectedValue.Equals("1") || rbtnFixedAmountTab1.SelectedValue.Equals("2"))
{
LoadGrid();
hdfremovecommIDs.Value = string.Empty;
HiddenFieldForChange.Value = string.Empty;
}
else
{
rbtnFixedAmountTab1.Items.FindByText(AgentCommisionConfiguration.Rows[0]["CommissionDescription"].ToString()).Selected = true;
}
grvViewFixedAgentCommisionConfiguration.DataSource = AgentCommisionConfiguration;
grvViewFixedAgentCommisionConfiguration.DataBind();
AgentCommissionType = AgentCommisionConfiguration.Rows[0]["CommissionDescription"].ToString();
ViewState["ViewAgentCommission"] = AgentCommisionConfiguration;
}
}
catch (Exception Ex)
{
_clsCommandFunctions.writeLog("Exception Occured :\n ." + Ex.Message);
}
}
enter code here
protected void rbtnFixedAmountTab1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (DateTime.Now.ToString("dd") == Convert.ToString(ConfigurationManager.AppSettings["StartOfDate"]))
{
fillAgentCommisionData();
if (rbtnFixedAmountTab1.SelectedIndex == 0)
{
grvViewFixedAgentCommisionConfiguration.Columns[4].Visible = false;
grvViewFixedAgentCommisionConfiguration.Columns[5].Visible = true;
}
else if (rbtnFixedAmountTab1.SelectedIndex == 1)
{
grvViewFixedAgentCommisionConfiguration.Columns[4].Visible = true;
grvViewFixedAgentCommisionConfiguration.Columns[5].Visible = false;
}
}
else
{
if (rbtnFixedAmountTab1.SelectedIndex == 1)
{
rbtnFixedAmountTab1.SelectedValue = "1";
}
else
{
rbtnFixedAmountTab1.SelectedValue = "2";
}
string DateValue = Convert.ToString(ConfigurationManager.AppSettings["StartOfDate"]);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Commission type can be change only on " + DateValue + " Date of month.');", true);
}
}
ModalPopupBranchWiseTotalAllocatedPopup.Show();
}
catch (Exception ex)
{
AppLog.ErrorLog(sender, ex);
ScriptManager.RegisterStartupScript(this.Page, typeof(string), "msg", "alert('Alarm: Contact system administrator');", true);
}
}
protected void grvViewFixedAgentCommisionConfiguration_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
RowIndexFromGV = Convert.ToInt32(RowIndexFromGV + 1); // For storing Initial index of gridId
TextBox txtFixedAmountTabMinCount = (TextBox)e.Row.FindControl("txtFixedAmountTabMinCount");
TextBox txtMaxCount = (TextBox)e.Row.FindControl("txtMaxCount");
DropDownList ddlCommissionType = (DropDownList)e.Row.FindControl("ddlCommissionType");
TextBox txtInterest = (TextBox)e.Row.FindControl("txtInterest");
TextBox txtFixedAmount = (TextBox)e.Row.FindControl("txtFixedAmount");
Label lblcommissiontypeID = (Label)e.Row.FindControl("lblcommissiontypeID");
LinkButton btnRemoveAgentCommission = (LinkButton)e.Row.FindControl("btnRemoveAgentCommission");
DataTable AgentCommisionConfiguration = new DataTable();
AgentCommisionConfiguration = MobilePortalProcess.GetEditedAgentWiseCommisionDetails(AgentCode);
RowsCountFromGV = AgentCommisionConfiguration.Rows.Count;
string checkpostrowindex = e.Row.RowIndex.ToString();
if (!string.IsNullOrEmpty(hdfremovecommIDs.Value))
{
// This used for storing Index of after removing new row
int removedId = Convert.ToInt32(hdfremovecommIDs.Value) - 1;
if (removedId.ToString().Equals(checkpostrowindex))
{
btnRemoveAgentCommission.Visible = true;
}
}
else if (!string.IsNullOrEmpty(HiddenFieldForChange.Value))
{
int ViewAddedRow = Convert.ToInt32(HiddenFieldForChange.Value) - 1;
if (ViewAddedRow.ToString().Equals(checkpostrowindex))
{
btnRemoveAgentCommission.Visible = true;
}
}
else
if (RowsCountFromGV == RowIndexFromGV)
{
//For checking rowcount of gridview from pageload and after selected index change of radio button
btnRemoveAgentCommission.Visible = true;
}
if (rbtnFixedAmountTab1.SelectedValue == "1")
{
grvViewFixedAgentCommisionConfiguration.Columns[4].Visible = false;
grvViewFixedAgentCommisionConfiguration.Columns[5].Visible = true;
}
else
{
grvViewFixedAgentCommisionConfiguration.Columns[4].Visible = true;
grvViewFixedAgentCommisionConfiguration.Columns[5].Visible = false;
}
}
ModalPopupBranchWiseTotalAllocatedPopup.Show();
}
catch (Exception Ex)
{
_clsCommandFunctions.writeLog("Exception Occured :\n ." + Ex.Message);
}
}
private void SetPreviousAgentCommission()
{
try
{
int rowIndex = 0;
if (ViewState["ViewAgentCommission"] != null)
{
DataTable dt = (DataTable)ViewState["ViewAgentCommission"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Label RowNumber = (Label)grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[1].FindControl("RowNumber");
TextBox txtFixedAmountTabMinCount = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[1].FindControl("txtFixedAmountTabMinCount");
TextBox txtMaxCount = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[2].FindControl("txtMaxCount");
DropDownList ddlCommissionType = (DropDownList)grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[3].FindControl("ddlCommissionType");
TextBox txtInterest = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[4].FindControl("txtInterest");
TextBox txtFixedAmount = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowIndex].Cells[5].FindControl("txtFixedAmount");
RowNumber.Text = Convert.ToString(rowIndex + 1);
txtFixedAmountTabMinCount.Text = dt.Rows[i]["MinCount"].ToString();
txtMaxCount.Text = dt.Rows[i]["MaxCount"].ToString();
ddlCommissionType.SelectedValue = dt.Rows[i]["CommissionType"].ToString();
txtInterest.Text = dt.Rows[i]["AgentWiseCommission"].ToString();
txtFixedAmount.Text = dt.Rows[i]["FixedAmount"].ToString();
rowIndex++;
}
}
}
}
catch (Exception Ex)
{
_clsCommandFunctions.writeLog("Exception Occured :\n ." + Ex.Message);
}
}
protected void grvViewFixedAgentCommisionConfiguration_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
string _CommandName = Convert.ToString(e.CommandName);
if (_CommandName == "AddCommssionDetails")
{
if (confirmValue.Value.ToString().Trim().Equals("Yes"))
{
if (DateTime.Now.ToString("dd") == Convert.ToString(ConfigurationManager.AppSettings["StartOfDate"]))
{
int rowindex = 0;
if (ViewState["ViewAgentCommission"] != null)
{
DataTable dtAgentComission = (DataTable)ViewState["ViewAgentCommission"];
DataRow drCurrentRow = null;
if (grvViewFixedAgentCommisionConfiguration.Rows.Count > 0)
{
int rowindex2 = grvViewFixedAgentCommisionConfiguration.Rows.Count - 1;
for (int i = 1; i <= grvViewFixedAgentCommisionConfiguration.Rows.Count; i++)
{
Label RowNumber = (Label)grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[1].FindControl("RowNumber");
TextBox txtFixedAmountTabMinCount = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[1].FindControl("txtFixedAmountTabMinCount");
TextBox txtMaxCount = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[2].FindControl("txtMaxCount");
DropDownList ddlCommissionType = (DropDownList)grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[3].FindControl("ddlCommissionType");
TextBox txtInterest = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[4].FindControl("txtInterest");
TextBox txtFixedAmount = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[5].FindControl("txtFixedAmount");
Label lblCommissionType = (Label)grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[6].FindControl("lblCommissionType");
Label lblCommissionTypeName = (Label)grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[7].FindControl("lblCommissionTypeName");
drCurrentRow = dtAgentComission.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtAgentComission.Rows[i - 1]["MinCount"] = txtFixedAmountTabMinCount.Text;
dtAgentComission.Rows[i - 1]["MaxCount"] = txtMaxCount.Text;
dtAgentComission.Rows[i - 1]["CommissionType"] = ddlCommissionType.SelectedValue.ToString();
dtAgentComission.Rows[i - 1]["AgentWiseCommission"] = txtInterest.Text;
dtAgentComission.Rows[i - 1]["FixedAmount"] = txtFixedAmount.Text;
dtAgentComission.Rows[i - 1]["CommissionType"] = lblCommissionType.Text;
dtAgentComission.Rows[i - 1]["CommissionDescription"] = lblCommissionTypeName.Text;
rowindex++;
}
if ((dtAgentComission.Rows[rowindex2]["MinCount"] != "") && (dtAgentComission.Rows[rowindex2]["MaxCount"] != "") && ((dtAgentComission.Rows[rowindex2]["AgentWiseCommission"] != "") || (dtAgentComission.Rows[rowindex2]["FixedAmount"] != "")) || (dtAgentComission.Rows[rowindex2]["CommissionType"] != ""))
{
dtAgentComission.Rows.Add(drCurrentRow);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Kindly filled records and click on save button first to add new row.');", true);
}
ViewState["ViewAgentCommission"] = dtAgentComission;
//start of region for hidden field for storing row id value
int CurrentTotalRowCount = dtAgentComission.Rows.Count;
HiddenFieldForChange.Value = CurrentTotalRowCount.ToString();
//End of region for hidden field for storing row id value grvViewFixedAgentCommisionConfiguration.DataSource = dtAgentComission;
grvViewFixedAgentCommisionConfiguration.DataBind();
}
SetPreviousAgentCommission();
}
}
else
{
string DateValue = Convert.ToString(ConfigurationManager.AppSettings["StartOfDate"]);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Commission type can be change only on " + DateValue + " Date of month.');", true);
}
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('You clicked Cancel.');", true);
}
ModalPopupBranchWiseTotalAllocatedPopup.Show();
}
if (_CommandName == "RemoveAgentCommission")
{
if (confirmValue.Value.ToString().Trim().Equals("Yes"))
{
if (DateTime.Now.ToString("dd") == Convert.ToString(ConfigurationManager.AppSettings["StartOfDate"]))
{
DataTable dtRemoveAgentComission = (DataTable)ViewState["ViewAgentCommission"];
DataRow drCurrentRow = null;
LinkButton lnkBtn = (LinkButton)e.CommandSource;
GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent;
int rowindex = myRow.RowIndex;
hdfremovecommIDs.Value = rowindex.ToString(); // For storing latest index of row for showing row removal option to the latest row.
int rowIndex1 = 0;
if (dtRemoveAgentComission.Rows.Count > 1)
{
for (int i = 1; i <= grvViewFixedAgentCommisionConfiguration.Rows.Count; i++)
{
Label RowNumber = (Label)grvViewFixedAgentCommisionConfiguration.Rows[rowIndex1].Cells[1].FindControl("RowNumber");
TextBox txtFixedAmountTabMinCount = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowIndex1].Cells[1].FindControl("txtFixedAmountTabMinCount");
TextBox txtMaxCount = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowIndex1].Cells[2].FindControl("txtMaxCount");
DropDownList ddlCommissionType = (DropDownList)grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[3].FindControl("ddlCommissionType");
TextBox txtInterest = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowIndex1].Cells[4].FindControl("txtInterest");
TextBox txtFixedAmount = (TextBox)grvViewFixedAgentCommisionConfiguration.Rows[rowIndex1].Cells[5].FindControl("txtFixedAmount");
Label lblCommissionType = (Label)grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[6].FindControl("lblCommissionType");
Label lblCommissionTypeName = (Label)grvViewFixedAgentCommisionConfiguration.Rows[rowindex].Cells[7].FindControl("lblCommissionTypeName");
drCurrentRow = dtRemoveAgentComission.NewRow();
dtRemoveAgentComission.Rows[i - 1]["MinCount"] = txtFixedAmountTabMinCount.Text;
dtRemoveAgentComission.Rows[i - 1]["MaxCount"] = txtMaxCount.Text;
dtRemoveAgentComission.Rows[i - 1]["CommissionType"] = ddlCommissionType.SelectedValue.ToString();
dtRemoveAgentComission.Rows[i - 1]["AgentWiseCommission"] = txtInterest.Text;
dtRemoveAgentComission.Rows[i - 1]["FixedAmount"] = txtFixedAmount.Text;
dtRemoveAgentComission.Rows[i - 1]["CommissionType"] = lblCommissionType.Text;
dtRemoveAgentComission.Rows[i - 1]["CommissionDescription"] = lblCommissionTypeName.Text;
rowIndex1++;
} dtRemoveAgentComission.Rows.Remove(dtRemoveAgentComission.Rows[rowindex]);
ViewState["VW_gvAgentcommission"] = dtRemoveAgentComission;
grvViewFixedAgentCommisionConfiguration.DataSource = dtRemoveAgentComission;
grvViewFixedAgentCommisionConfiguration.DataBind();
AgentCode = lblAgentCode.Text;
ViewAgentCommissionData = MobilePortalProcess.ViewEditAgentRangeWiseCommissionData(rowIndex1, AgentCode);
if (grvViewFixedAgentCommisionConfiguration.Rows.Count > 0)
{
if (ViewAgentCommissionData.Tables[0] != null)
{
if (ViewAgentCommissionData.Tables[0].Rows.Count > 0)
{
string AgentCodeData = string.Empty;
string MiCount = string.Empty;
string MaxCount = string.Empty;
string CommissionType = string.Empty;
string CommissionDescription = string.Empty; MiCount = ViewAgentCommissionData.Tables[0].Rows[0]["MinCount"].ToString();
MaxCount = ViewAgentCommissionData.Tables[0].Rows[0]["MaxCount"].ToString();
string FixedAmount = ViewAgentCommissionData.Tables[0].Rows[0]["FixedAmount"].ToString() == "" ? string.Empty : ViewAgentCommissionData.Tables[0].Rows[0]["FixedAmount"].ToString();
string AgentWiseCommission = ViewAgentCommissionData.Tables[0].Rows[0]["AgentWiseCommission"].ToString() == "" ? string.Empty : ViewAgentCommissionData.Tables[0].Rows[0]["AgentWiseCommission"].ToString();
CommissionDescription = ViewAgentCommissionData.Tables[0].Rows[0]["CommissionDescription"].ToString(); RemoveEditAgentWiseIndividualCommission(
Convert.ToString(rowIndex1),
MiCount, MaxCount, CommissionType, CommissionDescription, FixedAmount, AgentWiseCommission,
Convert.ToString(Session["Username"]), AgentCode);
}
}
}
}
}
else
{
string DateValue = Convert.ToString(ConfigurationManager.AppSettings["StartOfDate"]);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Commission type can be change only on " + DateValue + " Date of month.');", true);
}
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('You clicked Cancel.');", true);
}
ModalPopupBranchWiseTotalAllocatedPopup.Show();
}
}
catch (Exception Ex)
{
_clsCommandFunctions.writeLog("Exception Occured :\n ." + Ex.Message);
}
}
private void RemoveEditAgentWiseIndividualCommission(string RowIndex, string MinCount, string MaxCount, string CommissionTypeID, string CommissionDescription, string FixedAmount, string PercentageInterest, string CreatedBy, string AgentCodeData)
{
try
{
RemoveAgentWiseCommission = MobilePortalProcess.RemoveEditAgentWiseIndividualCommission(RowIndex, MinCount, MaxCount, CommissionTypeID, CommissionDescription, FixedAmount, PercentageInterest, CreatedBy, AgentCodeData);
if (RemoveAgentWiseCommission.Rows.Count > 0)
{
ScriptManager.RegisterStartupScript(this.Page, typeof(string), "msg", "alert('AgentWise Commission Slab Removed Successfully.');window.location='../AgencyBanking/AgentEditCommissionConfiguration.aspx';", true);
}
else
{
ScriptManager.RegisterStartupScript(this.Page, typeof(string), "msg", "alert('Contact system administrator.');window.location='../AgencyBanking/AgentEditCommissionConfiguration.aspx';", true);
}
}
catch (Exception Ex)
{ _clsCommandFunctions.writeLog("Exception Occured :\n ." + Ex.Message);
}
}
I have a gridview where I'm allowing user to select items for billing. now my problem is that the user is able to select same item twice in only one bill.
screen for reference:
Here the user is able to select duplicate items in the list which is not good.
my ASPX Markup:
<asp:GridView ID="Gridview1" runat="server" CssClass="table table-bordered table-hover table-responsive" ShowFooter="True" AutoGenerateColumns="False" OnRowDataBound="gvRowDataBound" OnRowDeleting="Gridview1_RowDeleting1" EmptyDataText="Data Not Available">
<Columns>
<asp:CommandField ShowDeleteButton="true" ControlStyle-CssClass="btn btn-danger fa fa-trash" DeleteText="" HeaderText="Remove Items" />
<asp:BoundField DataField="RowNumber" HeaderText="Sl. No." />
<asp:TemplateField HeaderText="Item Name" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:DropDownList ID="drpItemname" runat="server" Width="200px" CssClass="form-control select2" OnSelectedIndexChanged="GetItemDetails" AutoPostBack="true"></asp:DropDownList>
</ItemTemplate>
<HeaderStyle Wrap="False" />
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="HSN Code" Visible="false" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txthsn" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Available Quantity" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtQttyAvailable" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtQtty" runat="server" CssClass="form-control" OnTextChanged="CalculateTotal" AutoPostBack="true" Enabled="true"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Price" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtUnitPrice" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Discount" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtdisc" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S.GST" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtsgst" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="C.GST" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtcgst" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="I.GST" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtigst" runat="server" AutoPostBack="true" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Price" ConvertEmptyStringToNull="False" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtTotalPrice" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" CssClass="btn btn-primary" Text="Add" OnClick="AddItem" CausesValidation="False" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My c# code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Mylogic();
SetInitialRow();
ce1.StartDate = DateTime.Now.AddDays(-60);
ce1.SelectedDate = DateTime.Now.Date;
BindGrid();
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dt.Columns.Add(new DataColumn("Column4", typeof(string)));
dt.Columns.Add(new DataColumn("Column5", typeof(string)));
dt.Columns.Add(new DataColumn("Column6", typeof(string)));
dt.Columns.Add(new DataColumn("Column7", typeof(string)));
dt.Columns.Add(new DataColumn("Column8", typeof(string)));
dt.Columns.Add(new DataColumn("Column9", typeof(string)));
dt.Columns.Add(new DataColumn("Column10", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dr["Column5"] = string.Empty;
dr["Column6"] = string.Empty;
dr["Column7"] = string.Empty;
dr["Column8"] = string.Empty;
dr["Column9"] = string.Empty;
dr["Column10"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void GetItemDetails(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
foreach (GridViewRow row in Gridview1.Rows)
{
Control ctrl = row.FindControl("drpItemName") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
if (ddl.ClientID == ddl1.ClientID)
{
TextBox QttyAvailable = row.FindControl("txtQttyAvailable") as TextBox;
TextBox UnitPrice = row.FindControl("txtUnitPrice") as TextBox;
TextBox HsnCode = row.FindControl("txthsn") as TextBox;
TextBox Discount = row.FindControl("txtdisc") as TextBox;
TextBox SGST = row.FindControl("txtsgst") as TextBox;
TextBox CGST = row.FindControl("txtcgst") as TextBox;
TextBox IGST = row.FindControl("txtigst") as TextBox;
SqlConnection conn = new SqlConnection(constring);
conn.Open();
string str = "select * from Stock where itemname='" + ddl1.SelectedItem.ToString() + "'";
SqlCommand com = new SqlCommand(str, conn);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
UnitPrice.Text = reader["unitprice"].ToString();
QttyAvailable.Text = reader["qtty"].ToString();
HsnCode.Text = reader["hsn"].ToString();
Discount.Text = reader["disc"].ToString();
SGST.Text = reader["sgst"].ToString();
CGST.Text = reader["cgst"].ToString();
IGST.Text = reader["igst"].ToString();
}
reader.Close();
conn.Close();
}
}
}
}
protected void CalculateTotal(object sender, EventArgs e)
{
TextBox txt = sender as TextBox;
foreach (GridViewRow row in Gridview1.Rows)
{
TextBox lblQty = row.FindControl("txtQttyAvailable") as TextBox;
TextBox lblReceiveQty = row.FindControl("txtQtty") as TextBox;
if (lblQty != null && lblReceiveQty != null)
{
int Qty = 0, ReceiveQty = 0;
if (!string.IsNullOrEmpty(lblQty.Text))
{
Qty = int.Parse(lblQty.Text);
}
if (!string.IsNullOrEmpty(lblReceiveQty.Text))
{
ReceiveQty = int.Parse(lblReceiveQty.Text);
}
if (ReceiveQty > Qty)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "swal", "swal('Required quantity can not ne greater than available stock!', 'Royal Riders, Vijayapura', 'warning');", true);
lblReceiveQty.Text = "";
lblReceiveQty.Focus();
}
else if (Qty >= ReceiveQty)
{
TextBox AQtty = row.FindControl("txtQttyAvailable") as TextBox;
TextBox QttyReq = row.FindControl("txtQtty") as TextBox;
TextBox UnitPrice = row.FindControl("txtUnitPrice") as TextBox;
TextBox TotPrice = row.FindControl("txtTotalPrice") as TextBox;
TextBox DiscountPrice = row.FindControl("txtdisc") as TextBox;
DropDownList ItemName = row.FindControl("drpItemname") as DropDownList;
Control ctrl = row.FindControl("txtQtty") as TextBox;
if (ctrl != null)
{
TextBox txt1 = (TextBox)ctrl;
if (txt.ClientID == txt1.ClientID)
{
decimal totamt = Convert.ToDecimal(QttyReq.Text) * Convert.ToDecimal(UnitPrice.Text);
decimal discountrate = (totamt) - (totamt * Convert.ToDecimal(DiscountPrice.Text)) / 100;
TotPrice.Text = discountrate.ToString("#,0.00");
}
}
}
}
}
}
public static decimal totalgst;
public static decimal totalnetamt;
public static Int32 InitialStock;
protected void gvRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList drpItemName = (e.Row.FindControl("drpItemName") as DropDownList);
foreach (GridViewRow row2 in Gridview1.Rows)
{
TextBox txt = row2.FindControl("txtTotalPrice") as TextBox;
txt.Text = "0";
}
drpItemName.DataSource = GetData("SELECT itemname FROM Stock where rem != '1'");
drpItemName.DataTextField = "itemname";
drpItemName.DataValueField = "itemname";
drpItemName.DataBind();
drpItemName.Items.Insert(0, new ListItem("Please select"));
}
}
private DataSet GetData(string query)
{
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
DropDownList box1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("drpItemName");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txthsn");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("txtQttyAvailable");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("txtQtty");
TextBox box5 = (TextBox)Gridview1.Rows[rowIndex].Cells[5].FindControl("txtUnitPrice");
TextBox box6 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("txtdisc");
TextBox box7 = (TextBox)Gridview1.Rows[rowIndex].Cells[7].FindControl("txtsgst");
TextBox box8 = (TextBox)Gridview1.Rows[rowIndex].Cells[8].FindControl("txtcgst");
TextBox box9 = (TextBox)Gridview1.Rows[rowIndex].Cells[9].FindControl("txtigst");
TextBox box10 = (TextBox)Gridview1.Rows[rowIndex].Cells[10].FindControl("txtTotalPrice");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;
dtCurrentTable.Rows[i - 1]["Column6"] = box6.Text;
dtCurrentTable.Rows[i - 1]["Column7"] = box7.Text;
dtCurrentTable.Rows[i - 1]["Column8"] = box8.Text;
dtCurrentTable.Rows[i - 1]["Column9"] = box9.Text;
dtCurrentTable.Rows[i - 1]["Column10"] = box10.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList box1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("drpItemName");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txthsn");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("txtQttyAvailable");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("txtQtty");
TextBox box5 = (TextBox)Gridview1.Rows[rowIndex].Cells[5].FindControl("txtUnitPrice");
TextBox box6 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("txtdisc");
TextBox box7 = (TextBox)Gridview1.Rows[rowIndex].Cells[7].FindControl("txtsgst");
TextBox box8 = (TextBox)Gridview1.Rows[rowIndex].Cells[8].FindControl("txtcgst");
TextBox box9 = (TextBox)Gridview1.Rows[rowIndex].Cells[9].FindControl("txtigst");
TextBox box10 = (TextBox)Gridview1.Rows[rowIndex].Cells[10].FindControl("txtTotalPrice");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
box5.Text = dt.Rows[i]["Column5"].ToString();
box6.Text = dt.Rows[i]["Column6"].ToString();
box7.Text = dt.Rows[i]["Column7"].ToString();
box8.Text = dt.Rows[i]["Column8"].ToString();
box9.Text = dt.Rows[i]["Column9"].ToString();
box10.Text = dt.Rows[i]["Column10"].ToString();
rowIndex++;
if (!string.IsNullOrEmpty(box10.Text) && !string.IsNullOrEmpty(box10.Text))
{
box10.Text = dt.Rows[i]["Column10"].ToString();
}
else
{
box10.Text = "0";
}
}
}
}
}
protected void Confirm(object sender, EventArgs e)
{
decimal sum = 0;
decimal grandgst = 0;
try
{
foreach (GridViewRow g12 in Gridview1.Rows)
{
Control ctrl2 = g12.FindControl("txtigst") as TextBox;
if (ctrl2 != null)
{
TextBox txt1 = (TextBox)ctrl2;
TextBox cgst = g12.FindControl("txtcgst") as TextBox;
TextBox sgst = g12.FindControl("txtsgst") as TextBox;
TextBox igst = g12.FindControl("txtigst") as TextBox;
TextBox linegst = g12.FindControl("txtTotalPrice") as TextBox;
TextBox totamt = g12.FindControl("txtTotalPrice") as TextBox;
sum += decimal.Parse(((TextBox)(g12.Cells[10].FindControl("txtTotalPrice"))).Text);
decimal fcgst = Convert.ToDecimal(totamt.Text) * Convert.ToDecimal(cgst.Text) / 100;
decimal fsgst = Convert.ToDecimal(totamt.Text) * Convert.ToDecimal(sgst.Text) / 100;
decimal figst = Convert.ToDecimal(totamt.Text) * Convert.ToDecimal(igst.Text) / 100;
decimal ftot = Convert.ToDecimal(totamt.Text);
totalgst = fcgst + fsgst + figst;
grandgst += totalgst;
totalnetamt = grandgst + sum;
}
}
lblGstTotal.Text = grandgst.ToString();
lblGTotal.Text = sum.ToString();
lblGrandTotal.Text = (sum + grandgst).ToString();
foreach (GridViewRow g1 in Gridview1.Rows)
{
string ITEMNAME = (g1.FindControl("drpItemname") as DropDownList).Text;
string HSN = (g1.FindControl("txthsn") as TextBox).Text;
string QTY = (g1.FindControl("txtQtty") as TextBox).Text;
string UP = (g1.FindControl("txtUnitPrice") as TextBox).Text;
string DIS = (g1.FindControl("txtdisc") as TextBox).Text;
string SGST = (g1.FindControl("txtsgst") as TextBox).Text;
string CGST = (g1.FindControl("txtcgst") as TextBox).Text;
string IGST = (g1.FindControl("txtigst") as TextBox).Text;
string TOT = (g1.FindControl("txtTotalPrice") as TextBox).Text;
string InsertQuery = "Insert into Sales(bno,cdate,ctime,name,mobileno,address,gstno,pan,description,hsn,qtty,rate,disc,sgst,cgst,igst,linetotal,netamt,totalgst,grsamt,status,rem) values(#bno,#cdate,#ctime, #name, #mobileno, #address, #gstno, #pan, #description, #hsn, #qtty, #rate, #disc, #sgst, #cgst,#igst,#linetotal,#netamt,#totalgst,#grsamt,'1','0')";
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(InsertQuery, con))
{
cmd.Parameters.AddWithValue("#bno", Convert.ToInt64(lblBillNo.Text));
cmd.Parameters.AddWithValue("#cdate", txtBDate.Text.ToString());
cmd.Parameters.AddWithValue("#ctime", systemtime.ToString());
cmd.Parameters.AddWithValue("#name", txtcname.Text);
cmd.Parameters.AddWithValue("#mobileno", txtcmobile.Text);
cmd.Parameters.AddWithValue("#address", txtcaddress.Text);
cmd.Parameters.AddWithValue("#gstno", txtgst.Text);
cmd.Parameters.AddWithValue("#pan", txtcpan.Text);
cmd.Parameters.AddWithValue("#description", ITEMNAME);
cmd.Parameters.AddWithValue("#hsn", HSN);
cmd.Parameters.AddWithValue("#qtty", QTY);
cmd.Parameters.AddWithValue("#rate", Convert.ToDecimal(UP));
cmd.Parameters.AddWithValue("#disc", Convert.ToDecimal(DIS));
cmd.Parameters.AddWithValue("#sgst", Convert.ToDecimal(SGST));
cmd.Parameters.AddWithValue("#cgst", Convert.ToDecimal(CGST));
cmd.Parameters.AddWithValue("#igst", Convert.ToDecimal(IGST));
cmd.Parameters.AddWithValue("#linetotal", Convert.ToDecimal(TOT));
cmd.Parameters.AddWithValue("#grsamt", (lblGTotal.Text));
cmd.Parameters.AddWithValue("#totalgst", Convert.ToDecimal(lblGstTotal.Text));
cmd.Parameters.AddWithValue("#netamt", Convert.ToDecimal(lblGrandTotal.Text));
int i = cmd.ExecuteNonQuery();
if(i > 0)
{
DropDownList ItemName = g1.FindControl("drpItemname") as DropDownList;
TextBox ReqQtty = g1.FindControl("txtQtty") as TextBox;
using (SqlConnection DeductStockCon = new SqlConnection(constring))
{
string query = "update Stock set qtty=CAST(IsNULL(qtty, '0') as int) - '" + Convert.ToInt32(ReqQtty.Text) + "' where itemname='" + ItemName.SelectedItem.ToString() + "'";
DeductStockCon.Open();
using (SqlCommand DeductStockCmd = new SqlCommand(query, DeductStockCon))
{
int j = DeductStockCmd.ExecuteNonQuery();
if (j > 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "swal", "swal('Items inserted successfully!', 'Royal Riders, Vijayapura', 'success');", true);
}
}
}
}
}
}
}
LoadReceipt();
Clear();
Mylogic();
SetInitialRow();
}
catch (Exception ex)
{
throw ex;
}
}
private void Clear()
{
txtcname.Text = "";
txtcmobile.Text = "";
txtcaddress.Text = "";
txtcpan.Text = "";
txtgst.Text = "";
drpMode.SelectedValue = "--Select Payment Mode--";
}
private void Mylogic()
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT MAX(bno) + 1 as Billno FROM Sales", con))
lblBillNo.Text = cmd.ExecuteScalar().ToString();
con.Close();
}
}
protected void AddItem(object sender, EventArgs e)
{
try
{
AddNewRowToGrid();
decimal sum = 0;
foreach (GridViewRow row1 in Gridview1.Rows)
{
TextBox val1 = row1.FindControl("txtTotalPrice") as TextBox;
if (!string.IsNullOrEmpty(val1.Text) && !string.IsNullOrEmpty(val1.Text))
{
sum += 0;
}
else
{
sum += decimal.Parse(((TextBox)(row1.Cells[10].FindControl("txtTotalPrice"))).Text);
}
}
lblGTotal.Text = sum.ToString();
}
catch (Exception ex)
{
lblGTotal.Text = ex.Message.ToString();
}
}
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
SetInitialRow();
BindGrid();
}
protected void BindGrid()
{
Gridview1.DataSource = ViewState["CurrentTable"] as DataTable;
Gridview1.DataBind();
}
private void LoadReceipt()
{
SqlConnection CN;
string MyConnectionString = null;
MyConnectionString = constring;
CN = new SqlConnection(MyConnectionString);
CN.Open();
string SQL = null;
SQL = "SELECT * FROM Sales where bno=(select max(bno) as 'Billno' from Sales)";
SqlDataAdapter myDA = new SqlDataAdapter(SQL, CN);
CN.Close();
SalesDataset DS = new SalesDataset();
myDA.Fill(DS, "Sales");
ReportDocument myRPT = new ReportDocument();
myRPT.Load(Server.MapPath("Reports/BillReciept.rpt"));
myRPT.SetDataSource(DS);
rptSales.ReportSource = myRPT;
rptSales.SeparatePages = false;
}
protected void btnLastReport_Click(object sender, EventArgs e)
{
LoadReceipt();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1)
{
if (gvRow.RowIndex < dt.Rows.Count - 1)
{
dt.Rows.Remove(dt.Rows[rowID]);
ResetRowID(dt);
}
}
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
SetPreviousData();
}
private void ResetRowID(DataTable dt)
{
int rowNumber = 1;
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
row[0] = rowNumber;
rowNumber++;
}
}
}
protected void Gridview1_RowDeleting1(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
dt.Rows.RemoveAt(e.RowIndex);
Gridview1.DataSource = dt;
Gridview1.DataBind();
SetPreviousData();
if(Gridview1.Rows.Count <= 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "swal", "swal('This is the only item in the list!', 'Royal Riders, Vijayapura', 'success');", true);
SetInitialRow();
}
}
You can do it in two ways
Handle the code in GetItemDetails() Event Method do a foreach and check if the name selected in the drpItemname dropdown eqauls with the name of any of the previous drpItemname dropdownlist of the gridview
In the Method AddNewRowToGrid() before binding data to drpItemname dropdown remove those values from the list which are already selected in the previous drpItemname dropdown and then bind it and add row [Note this will work ambiguos because if user changes the dropdownvalue of previous list then you will get problem ]
Are these ideas helpfull ?
Ex 1 -
protected void GetItemDetails(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
foreach (GridViewRow row in Gridview1.Rows)
{
Control ctrl = row.FindControl("drpItemName") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
if((ddl1.ClientId != ddl.ClientId) && (ddl1.SelectedIndex == ddl.SelectedIndex)){
return Response.Write("Error") //
}
}
}
}
I have dynamically created Data Table bind to Grid View. In every row I'm adding button which i'm define in grid view. Now I want that button to call in another button click event and make modifications in values.Is that possible?Here is my code:
<asp:GridView ID="GridView2" runat="server" OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnTest" runat="server" CommandName="odzemi" CssClass="button2" OnClick="btnTest_Click" Text="-" Width="100px" Font-Bold="True" />
<asp:Button ID="Button15" Visible="false" runat="server" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter1"] = newValue;
Session["Counter"] = newValue;
if (Session["Markici"] != null || Session["Markici"] != null)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
/*decimal*/ old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
// decimal pocentDanok0 = 0.0m;
// decimal pocentDanok1 = 0.18m;
// decimal pocentDanok2 = 0.5m;
//int oldValue = int.Parse(old);
/* decimal*/ newValue = old - 1; //
Label37.Text = newValue.ToString();
decimal newIznos = oldIznos - Convert.ToDecimal(Cena1);
dtCurrentTable.Rows[clickedIndex].SetField("Kolicina", newValue.ToString());
dtCurrentTable.Rows[clickedIndex].SetField("VkIznos", newIznos.ToString());
}
//I want here to call btn_test click and modyfy his values
protected void Button7_Click(object sender, EventArgs e)
{
if (GridView2.Rows.Count == 0)
{
Response.Redirect("MasiGradskaKafanak1.aspx");
}
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["string2"].ConnectionString);
Session["Counter"] = counter;
Label11.Text = counter.ToString();
// Label11.Text = Session["kolicina2"].ToString(); //ViewState["count"].ToString(); //
if (reader.Read())
{
Label35.Text = (string)reader["pkid"].ToString();
Label12.Text = (string)reader["Artikal"].ToString();
Label33.Text = (string)reader["Vid"].ToString();
Label34.Text = (string)reader["EdMera"].ToString();
Label14.Text = (string)reader["TarifaID"].ToString();
Label13.Text = (string)reader["Cena1"].ToString();
//iznos
decimal mnoz = Convert.ToDecimal(Label11.Text) * Convert.ToDecimal(Label13.Text);
Label17.Text = mnoz.ToString();
decimal.Parse(Label17.Text);
decimal cena;
cena = Convert.ToDecimal(Label13.Text);
decimal kolicina;
kolicina = Convert.ToDecimal(Label11.Text);
decimal iznos;
iznos = Convert.ToDecimal(Label17.Text);
Session["cena1"] = Label13.Text;
Session["iznos1"] = Label17.Text;
if (Label14.Text == "0")
{
decimal pocentDanok = 0.0m;
vkdanok1 = Convert.ToDecimal(vkdanok1) + Convert.ToDecimal(cena) * Convert.ToDecimal(kolicina) * Convert.ToDecimal(pocentDanok) / (1 + Convert.ToDecimal(pocentDanok));
vkdanok1 = Math.Truncate(vkdanok1 * 10000m) / 10000m;
Label18.Text = vkdanok.ToString();//vkdanok
}
else if (Label14.Text == "1")
{
decimal pocentDanok = 0.18m;
vkdanok1 = (vkdanok1) + Convert.ToDecimal(cena) * Convert.ToDecimal(kolicina) * Convert.ToDecimal(pocentDanok) / (1 + Convert.ToDecimal(pocentDanok));
vkdanok1 = Math.Truncate(vkdanok1 * 10000m) / 10000m;
Label18.Text = vkdanok1.ToString();//VkDanok
}
else if (Label14.Text == "2")
{
decimal pocentDanok = 0.5m;
vkdanok1 = Convert.ToDecimal(vkdanok1) + Convert.ToDecimal(cena) * Convert.ToDecimal(kolicina) * Convert.ToDecimal(pocentDanok) / (1 + Convert.ToDecimal(pocentDanok));
vkdanok1 = Math.Truncate(vkdanok1 * 10000m) / 10000m;
Label18.Text = vkdanok1.ToString();//vkdanok
}
conn.Close();
}
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
if (Label37.Text == "0")
{
dtCurrentTable.Rows[0]["Kolicina"] = Label11.Text;
}
else if (Label37.Text != "0")
{
Counter1 = Counter1 + 1;
dtCurrentTable.Rows[0]["Kolicina"] = Convert.ToInt32(Label37.Text) + Counter1;// Label37.Text;//Convert.ToInt32(Label37.Text) + 3;
}
dtCurrentTable.Rows[0]["Artikal"] = Label12.Text;
dtCurrentTable.Rows[0]["Cena1"] = Label13.Text;
dtCurrentTable.Rows[0]["VkIznos"] = Label17.Text;
dtCurrentTable.Rows[0]["VkDanok"] = Label18.Text;
dtCurrentTable.Rows[0]["EdMera"] = Label34.Text;
dtCurrentTable.Rows[0]["ArtikalID"] = Label35.Text;
dtCurrentTable.Rows[0]["Vid"] = Label33.Text;
dtCurrentTable.Rows[0]["TarifaID"] = Label14.Text;
dtCurrentTable.AcceptChanges();
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
RemoveDuplicates(dt);
}
You can use the EditItemTemplate to corresponding every templatefield in gridview.
Here is the code:
<%# Page Language="VB" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<script runat="server">
Dim SQLConn As SqlConnection = New SqlConnection()
Dim strSQL As String
Dim strFilter As String
Dim objCmd
Dim objReader As SqlDataReader
Dim DBComm As SqlCommand
Dim DBAdapt As SqlDataAdapter
Sub DBConnect
SQLConn.ConnectionString = ConfigurationSettings.AppSettings("CString")
SQLConn.Open()
End Sub
Sub DBDisconnect
SQLConn.close()
End Sub
Sub Page_Load
Dim ThisFilter As Object = ViewState("vsFilter")
If Not (ThisFilter Is Nothing) Then
strFilter = CStr(ThisFilter)
Else
strFilter = "All"
End If
If Not Page.IsPostBack Then
BindData(True)
End If
End Sub
Sub BindData(ByVal GetFresh As Boolean)
Call DBConnect()
Dim DTable As DataTable = Nothing
If ViewState("vsSortData") Is Nothing Or GetFresh Then
If Session("Agency_Name") = "Main Company" Then
strSQL = "SELECT LOGIN.Login_ID, LOGIN.Login_Last_Name + ', ' + LOGIN.Login_First_Name + ' ' + CASE WHEN Login_Middle_Name IS NULL THEN '' ELSE CONVERT(varchar, Login_Middle_Name) END AS FullName, AGENCY.Agency_Name, '(' + Substring(Login_Phone, 0, 4) + ') ' + Substring(Login_Phone, 4, 3) + '-' + Substring(Login_Phone, 7, 4) as Phone, LOGIN.Login_Email, CASE WHEN Login_Type = 'U' THEN 'User' WHEN Login_Type = 'I' THEN 'ISC' ELSE CONVERT(varchar, Login_Type) END AS LoginType, CASE WHEN Login_Account_Active = 'T' THEN 'Yes' WHEN Login_Account_Active = 'F' THEN 'No' ELSE CONVERT(varchar, Login_Account_Active) END AS AcctActive FROM LOGIN INNER JOIN AGENCY ON LOGIN.Login_Agency_ID = AGENCY.Agency_ID WHERE LOGIN.Login_Deleted = 'F'"
Else
strSQL = "SELECT LOGIN.Login_ID, LOGIN.Login_Last_Name + ', ' + LOGIN.Login_First_Name + ' ' + CASE WHEN Login_Middle_Name IS NULL THEN '' ELSE CONVERT(varchar, Login_Middle_Name) END AS FullName, AGENCY.Agency_Name, '(' + Substring(Login_Phone, 0, 4) + ') ' + Substring(Login_Phone, 4, 3) + '-' + Substring(Login_Phone, 7, 4) as Phone, LOGIN.Login_Email, CASE WHEN Login_Type = 'U' THEN 'User' WHEN Login_Type = 'I' THEN 'ISC' ELSE CONVERT(varchar, Login_Type) END AS LoginType, CASE WHEN Login_Account_Active = 'T' THEN 'Yes' WHEN Login_Account_Active = 'F' THEN 'No' ELSE CONVERT(varchar, Login_Account_Active) END AS AcctActive FROM LOGIN INNER JOIN AGENCY ON LOGIN.Login_Agency_ID = AGENCY.Agency_ID WHERE LOGIN.Login_Deleted = 'F' AND AGENCY.Agency_Name='" & Session("Agency_Name") & "'"
End If
DBComm = New SqlCommand(strSQL, SQLConn)
DBAdapt = New SqlDataAdapter(DBComm)
Dim DSet As New DataSet()
Try
DBAdapt.Fill(DSet)
DTable = DSet.Tables(0)
Catch EXC As SqlException
Me.lblMsg2.Text = EXC.Message
Return
Finally
SQLConn.Close()
End Try
ViewState("vsSortData") = DTable
Else
DTable = CType(ViewState("vsSortData"), DataTable)
End If
If strFilter = "All" Then
DTable.DefaultView.RowFilter = String.Empty
Else
DTable.DefaultView.RowFilter = "FullName LIKE '" & strFilter & "%'"
End If
Me.datagrid.DataSource = DTable.DefaultView
Me.datagrid.DataBind()
BuildAlphaPager()
Call DBDisconnect()
End Sub
Sub BuildAlphaPager()
Dim DTable As DataTable
If ViewState(("strLetter")) Is Nothing Then
Dim arrLetters As String() = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "All"}
DTable = New DataTable()
DTable.Columns.Add(New DataColumn("Letter", GetType(String)))
Dim i As Integer
For i = 0 To arrLetters.Length - 1
Dim DRow As DataRow = DTable.NewRow()
DRow(0) = arrLetters(i)
DTable.Rows.Add(DRow)
Next i
ViewState("strLetter") = DTable
Else
DTable = CType(ViewState("strLetter"), DataTable)
End If
Me.rptLetters.DataSource = DTable.DefaultView
Me.rptLetters.DataBind()
End Sub
Protected Sub rptLetters_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
If (e.Item.ItemType = ListItemType.Header) Then
ElseIf (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim lnkAlpha As LinkButton = CType(e.Item.FindControl("lnkAlpha"), LinkButton)
lnkAlpha.Text = DataBinder.Eval(e.Item.DataItem, "Letter")
lnkAlpha.CommandName = "Filter"
lnkAlpha.CommandArgument = DataBinder.Eval(e.Item.DataItem, "Letter")
Dim DRView As DataRowView = CType(e.Item.DataItem, DataRowView)
If CStr(DRView(0)) = strFilter Then
lnkAlpha.Enabled = False
End If
ElseIf (e.Item.ItemType = ListItemType.Footer) Then
End If
End Sub
Protected Sub rptLetters_ItemCommand(ByVal source As Object, ByVal e As RepeaterCommandEventArgs)
If e.CommandName = "Filter" Then
strFilter = CStr(e.CommandArgument)
ViewState("vsFilter") = strFilter
BindData(False)
End If
End Sub
</script>
<html>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form runat="server">
<font size="1" color="#FF0000"><strong><asp:label id="lblMsg2" runat="server" /></strong></font>
<div align="center"><h3>
<asp:Repeater ID="rptLetters" runat="server" OnItemDataBound="rptLetters_ItemDataBound" OnItemCommand="rptLetters_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lnkAlpha" runat="server" />
</ItemTemplate>
</asp:Repeater>
</h3></div>
<asp:DataGrid ID="datagrid" runat="server" AutoGenerateColumns="False" AllowSorting="true" width="725px" BackColor="Gray" BorderWidth="0" BorderStyle="None" BorderColor="#DEBA84" Font-Size="XX-Small" CellPadding="3" CellSpacing="1">
<HeaderStyle font-size="XX-Small" font-names="Verdana" font-bold="True" horizontalalign="Center" forecolor="White" bordercolor="White" backcolor="#1E3769" />
<AlternatingItemStyle BackColor = "Gray" CssClass = "row" />
<ItemStyle CssClass = "row" />
<Columns>
<asp:TemplateColumn ItemStyle-Width="200px" ItemStyle-HorizontalAlign="center" HeaderText="Full Name" SortExpression="Login_Last_Name">
<ItemTemplate> <a style="color: #000000;" href="mailto:<%# Container.DataItem("Login_Email")%>">
<%# Container.DataItem("FullName")%> </a> </ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn ItemStyle-Width="160px" ItemStyle-HorizontalAlign="center" DataField="Agency_Name" HeaderText="Agency Name" SortExpression="Agency_Name"></asp:BoundColumn>
<asp:BoundColumn ItemStyle-Width="110px" ItemStyle-HorizontalAlign="center" DataField="Phone" HeaderText="Phone Number" SortExpression="Login_Phone"></asp:BoundColumn>
<asp:BoundColumn ItemStyle-Width="80px" ItemStyle-HorizontalAlign="center" DataField="LoginType" HeaderText="User Type" SortExpression="Login_Type"></asp:BoundColumn>
<asp:BoundColumn ItemStyle-Width="115px" ItemStyle-HorizontalAlign="center" DataField="AcctActive" HeaderText="Account Active" SortExpression="Login_Account_Active"></asp:BoundColumn>
<asp:TemplateColumn ItemStyle-Width="40px" ItemStyle-HorizontalAlign="center" HeaderText="Details">
<ItemTemplate>
<a style="color: #000000;" href="javascript:openDetail('userDetail.aspx?id=<%# Container.DataItem("Login_ID")%>');">
Details </a> </ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn ItemStyle-Width="25px" ItemStyle-HorizontalAlign="center" HeaderText="Edit">
<ItemTemplate> <a style="color: #000000;" href="edAccounts.aspx?f=e&id=<%# Container.DataItem("Login_ID")%>">
Edit </a> </ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>
</body>
</html>
I just want the Full Name column (first column, FullName) to be in alphabetical order by default, and then if they click on a specific column then that column should arrange itself alphabetically. This used to work until I applied the above solution to paginate based on the letter in the name.
I have tried modifying the SQL queries and including "ORDER BY FullName" and "ORDER BY LOGIN.Login_Last_Name" and many other things but can't seem to get it to order by this by default, nor does any other column sort when clicked on as should occur. Somehow the alphabetic pagination is not allowing these fields to be sorted any further.
This is ASP.NET 2.0 with VB. Help?
I recommend this example and i as a personal note I would recommend using the example with the ObjectDataSource as it allows you to separate your presentation layer (pages) prom your data access layer (classes that execute sql and retrieve the data)
I am using telerik grid. I need to apply a filter for all the columns in my grid. Currenly I am customizing the filter option using the following code. By using the following code, I am removing the certain items for all the columns. But, for a date column could any one please tell me what are the possible options for filtering in the grid and how to customize those filtering options?
Code Behind
protected void RGVTest_Init(object sender, EventArgs e)
{
GridFilterMenu menu = RGVTest.FilterMenu;
int i = 0;
while (i < menu.Items.Count)
{
if (menu.Items[i].Text == "Between" ||
menu.Items[i].Text == "NotBetween")
{
menu.Items.RemoveAt(i);
}
else
{
i++;
}
}
}
*Aspx:*
<telerik:RadGrid ID="RGVTest" runat="server" Skin="Vista" AllowPaging="True"
AllowFilteringByColumn="true" AllowSorting="true" GridLines="None" OnItemCommand="RGVTest_ItemCommand"
PageSize="10" OnNeedDataSource="RGVTest_NeedDataSource" OnItemDataBound="RGVTest_ItemDataBound"
OnInit="RGVTest_Init">
<GroupingSettings CaseSensitive="false" />
<PagerStyle Mode="NextPrevAndNumeric" AlwaysVisible="true" />
<MasterTableView AutoGenerateColumns="False" CellSpacing="-1" >
<NoRecordsTemplate>
<div style="color: red">
No Records to display!
</div>
</NoRecordsTemplate>
<Columns>
<telerik:GridTemplateColumn DataField="SSN" ReadOnly="True" HeaderText="SSN" UniqueName="SSN"
SortExpression="SSN">
<ItemTemplate>
<asp:Label ID="LblSSN" runat="server" Text='<%#Eval("SSN") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" Width="5%" />
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn DataField="Date" HeaderText="Date" UniqueName="Date"
SortExpression="Date">
<ItemTemplate>
<asp:Label ID="LblDate" runat="server" Text='<%#Eval("Date","{0:MM/dd/yyyy}") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" Width="4%" />
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
you do like this way:
protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.FilterCommandName)
{
Pair filterPair = e.CommandArgument as Pair;
string columnName = Convert.ToString(filterPair.Second);
if (columnName == "CreationDate")
{
e.Canceled = true;
string date = ((TextBox)((GridFilteringItem)e.Item)[Convert.ToString(filterPair.Second)].Controls [0]).Text;
DateTime startDate = Convert.ToDateTime(date);
DateTime endDate = startDate.AddDays(1);
string newFilter = "('" + startDate.ToString("MM/dd/yyyy") + "' <= [CreationDate] AND [CreationDate] <= '" + endDate.ToString("MM/dd/yyyy") + "')";
GridBoundColumn dateColumn = (GridBoundColumn)e.Item.OwnerTableView.GetColumnSafe(columnName);
dateColumn.CurrentFilterValue = startDate.ToString("MM/dd/yyyy");
RadGrid1.MasterTableView.FilterExpression = newFilter;
RadGrid1.Rebind();
}
}
}
Try like this
function FilterMenuShowing(sender, eventArgs)
{
if (eventArgs.get_column().get_uniqueName() == "IsPostable")
{
var menu = eventArgs.get_menu();
var items = menu._itemData;
var i = 0;
while (i < items.length)
{
if (items[i].value != "NoFilter" && items[i].value != "EqualTo" && items[i].value != "NotEqualTo")
{
var item = menu._findItemByValue(items[i].value);
if (item != null)
item._element.style.display="none";
}
i++;
}
}
else
{
var menu = eventArgs.get_menu();
var items = menu._itemData;
var i = 0;
while (i < items.length)
{
var item = menu._findItemByValue(items[i].value);
if (item != null)
item._element.style.display="";
i++;
}
}
}
On your grid add-
<ClientSettings>
<ClientEvents OnFilterMenuShowing="filterMenuShowing" />
</ClientSettings>
See details here
You can try the way its done below for "order date" column.
protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.FilterCommandName &&
((Pair)e.CommandArgument).Second.ToString() == "OrderDate"
&&
((Pair)e.CommandArgument).First != "NoFilter")
{
e.Canceled = true;
GridFilteringItem filterItem = (GridFilteringItem)e.Item;
string currentPattern = (filterItem[((Pair)e.CommandArgument).Second.ToString()].Controls[0] as TextBox).Text;
string filterPattern = "";
string filterPatternAssist = "";
if (currentPattern.IndexOf(" ") != -1)
{
currentPattern = currentPattern.Replace(" ", "/");
}
string[] vals = currentPattern.Split("/".ToCharArray());
string filterOption = (e.CommandArgument as Pair).First.ToString();
if (filterOption != "IsNull" && filterOption != "NotIsNull")
{
if (vals.Length > 3)
{
filterPatternAssist = vals[4] + "/" + vals[3] + "/" + vals[5];
}
filterPattern = vals[1] + "/" + vals[0] + "/" + vals[2];
}
GridBoundColumn dateColumn = (GridBoundColumn)e.Item.OwnerTableView.GetColumnSafe("OrderDate");
switch (filterOption)
{
case "EqualTo":
filterPattern = "[OrderDate] = '" + filterPattern + "'";
dateColumn.CurrentFilterFunction = GridKnownFunction.EqualTo;
break;
case "NotEqualTo":
filterPattern = "Not [OrderDate] = '" + filterPattern + "'";
dateColumn.CurrentFilterFunction = GridKnownFunction.NotEqualTo;
break;
case "GreaterThan":
filterPattern = "[OrderDate] > '" + filterPattern + "'";
dateColumn.CurrentFilterFunction = GridKnownFunction.GreaterThan;
break;
case "LessThan":
filterPattern = "[OrderDate] < '" + filterPattern + "'";
dateColumn.CurrentFilterFunction = GridKnownFunction.LessThan;
break;
case "GreaterThanOrEqualTo":
filterPattern = "[OrderDate] >= '" + filterPattern + "'";
dateColumn.CurrentFilterFunction = GridKnownFunction.GreaterThanOrEqualTo;
break;
case "LessThanOrEqualTo":
filterPattern = "[OrderDate] <= '" + filterPattern + "'";
dateColumn.CurrentFilterFunction = GridKnownFunction.LessThanOrEqualTo;
break;
case "Between":
filterPattern = "'" + filterPattern + "' <= [OrderDate] AND [OrderDate] <= '" + filterPatternAssist + "'";
dateColumn.CurrentFilterFunction = GridKnownFunction.Between;
break;
case "NotBetween":
filterPattern = "[OrderDate] <= '" + filterPattern + "' OR [OrderDate] >= '" + filterPatternAssist + "'";
dateColumn.CurrentFilterFunction = GridKnownFunction.NotBetween;
break;
case "IsNull":
break;
case "NotIsNull":
break;
}
foreach (GridColumn column in RadGrid1.MasterTableView.Columns)
{
if (column.UniqueName != "OrderDate")
{
column.CurrentFilterFunction = GridKnownFunction.NoFilter;
column.CurrentFilterValue = string.Empty;
}
}
Session["filterPattern"] = filterPattern;
dateColumn.CurrentFilterValue = currentPattern;
filterItem.OwnerTableView.Rebind();
}
//Add more conditional checks for commands here if necessary
else if (e.CommandName != RadGrid.SortCommandName && e.CommandName != RadGrid.PageCommandName)
{
Session["filterPattern"] = null;
GridBoundColumn dateColumn = (GridBoundColumn)e.Item.OwnerTableView.GetColumnSafe("OrderDate");
dateColumn.CurrentFilterFunction = GridKnownFunction.NoFilter;
dateColumn.CurrentFilterValue = string.Empty;
}
}