Format Decimal number to Indian Currency Format - c#

I am using C# asp.net 4.0 in my project where i need to display price in India curreny format.
eg. my number is 12550000.00 then i want to display it as 1,25,50,000.00
But i want this to be displayed in gridview when i bind the data to the gridview,
so it can be done in markup page. where we place Eval for each Item Data Bound.
However, i would also like to explain my senario for displaying comma sepearted values.
i have a set of textboxes above the gridview where user makes entries of values and click add.
this gets add in the viewstate and the viewstate is binded to gridview.
In gridview i also have Edit button on click of it the values in viewstate is passed back to textbox on RowCommand Event of gridview. and on update click the viewstate datatable is updated and Binded back to gridview.
FOR your reference:
protected void gvPropertyConfig_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "EditItem")
{
int index = Convert.ToInt32(e.CommandArgument);
hdnIndex.Value = index.ToString();
DataTable dt = (DataTable)ViewState["proeprtyConfig"];
DataRow dr = dt.Rows[index];
if (Request.QueryString["CMD"] == "Edit")
{
hdnPropertyConfigID.Value = dr["config_id"].ToString();
if (dr["is_active"].ToString().ToLower() == "true")
{
chkConfigVisible.Checked = true;
}
else
{
chkConfigVisible.Checked = false;
}
thIsActHed.Visible = true;
tdIsActchk.Visible = true;
tdbtnConfig.ColSpan = 2;
}
txtScalableArea.Text = dr["scalable_area"].ToString();
txtCarpetArea.Text = dr["carpet_area"].ToString();
txtPricePerSqFt.Text = dr["price_per_sq_ft"].ToString();
txtCCPricePerSqFt.Text = dr["cc_price_per_sq_ft"].ToString();
txtTotalPrice.Text = dr["total_price"].ToString();
ddlNoOfBedrooms.SelectedValue = dr["room_id"].ToString();
btnUpdateConfig.Visible = true;
btnConfigSubmit.Visible = false;
}
if (e.CommandName == "DeleteItem")
{
int index = Convert.ToInt32(e.CommandArgument);
DataTable dt = (DataTable)ViewState["proeprtyConfig"];
DataRow dr = dt.Rows[index];
if (Request.QueryString["CMD"].ToString() == "Edit")
{
int PropertyConfigID = Convert.ToInt32(dr[0].ToString());
prConfigObj.deletePropertyConfig(PropertyConfigID);
fillData();
}
else
{
dr.Delete();
gvPropertyConfig.DataSource = (DataTable)ViewState["proeprtyConfig"];
gvPropertyConfig.DataBind();
}
clearConfigTextBoxes();
btnConfigSubmit.Visible = true;
btnUpdateConfig.Visible = false;
}
setChecklistAttr();
}
catch (Exception ex)
{
throw ex;
}
}
Below is the markup for Gridview,
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="tabBord">
<table>
<tr>
<td colspan="4" class="middle">
<h4>
Property Config Information</h4>
</td>
</tr>
<tr>
<td colspan="4">
<p>
Note: Enter total prices in lacs only. Eg. If 1 Crore than enter 1,00,00,000
</p>
<p>
</p>
</td>
</tr>
<tr>
<td>
<div id="divconfigstr" runat="server">
Configuration<span style="color: Red">*</span></div>
<%--class="displaynon"--%>
</td>
<td>
<div id="divnoofbedrooms" runat="server">
<asp:DropDownList Enabled="false" ID="ddlNoOfBedrooms" runat="server">
</asp:DropDownList>
<p>
</p>
</div>
</td>
<td>
Scalable Area <span style="color: Red">*</span>
</td>
<td>
<asp:TextBox ID="txtScalableArea" runat="server" autocomplete="off" MaxLength="10"></asp:TextBox><p>
</p>
</td>
</tr>
<tr>
<td>
Carpet Area <span style="color: Red">*</span>
</td>
<td>
<asp:TextBox ID="txtCarpetArea" runat="server" autocomplete="off" MaxLength="10"></asp:TextBox><p>
</p>
</td>
<td>
Price/Sq.Ft.<span style="color: Red">*</span>
</td>
<td>
<asp:TextBox ID="txtPricePerSqFt" runat="server" autocomplete="off" MaxLength="10"></asp:TextBox><p>
</p>
</td>
</tr>
<tr>
<td>
CC Price/Sq.Ft.<span style="color: Red">*</span>
</td>
<td>
<asp:TextBox ID="txtCCPricePerSqFt" runat="server" autocomplete="off" MaxLength="10"></asp:TextBox><p>
</p>
</td>
<td>
Total Price (in lacs)<span style="color: Red">*</span>
</td>
<td>
<asp:TextBox ID="txtTotalPrice" runat="server" autocomplete="off" MaxLength="10"></asp:TextBox><p>
</p>
</td>
</tr>
<tr>
<td id="thIsActHed" runat="server">
Active
<asp:HiddenField ID="hdnPropertyConfigID" runat="server" />
<asp:HiddenField ID="hdnIndex" runat="server" />
</td>
<td id="tdIsActchk" runat="server">
<asp:CheckBox ID="chkConfigVisible" runat="server" CssClass="checklist" /><p>
</p>
</td>
<td id="tdbtnConfig" runat="server" colspan="2">
<div class="btnHold">
<asp:Button ID="btnConfigSubmit" runat="server" Text="Add" OnClientClick="return ValidatePropertyConfig();"
CssClass="sendBtn" OnClick="btnConfigSubmit_Click" />
<asp:Button ID="btnUpdateConfig" runat="server" OnClick="btnUpdateConfig_Click" OnClientClick="return ValidatePropertyConfig();"
CssClass="sendBtn" Text="Update" Visible="False" />
<asp:Label ID="lblerrconfig" CssClass="errormsg" runat="server"></asp:Label>
</div>
</td>
</tr>
<tr>
<td colspan="4">
<div class="pHold">
<div class="gridH">
<asp:GridView ID="gvPropertyConfig" runat="server" AutoGenerateColumns="False" OnRowCommand="gvPropertyConfig_RowCommand"
OnRowDataBound="gvPropertyConfig_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="No Of Bedrooms" ItemStyle-CssClass="txtLT">
<ItemTemplate>
<asp:Label ID="lblno_of_bedrooms" runat="server" Text='<%# Eval("room_no") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Scalable Area" ItemStyle-CssClass="txtRT">
<EditItemTemplate>
<asp:TextBox ID="txtscalable_area" runat="server" Text='<%# Eval("scalable_area") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblscalable_area" runat="server" Text='<%# Eval("scalable_area") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Carpet Area" ItemStyle-CssClass="txtRT">
<EditItemTemplate>
<asp:TextBox ID="txtcarpet_area" runat="server" Text='<%# Eval("carpet_area") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcarpet_area" runat="server" Text='<%# Eval("carpet_area") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price/SqFt." ItemStyle-CssClass="txtRT">
<EditItemTemplate>
<asp:TextBox ID="txtprice_per_sq_ft" runat="server" Text='<%# Eval("price_per_sq_ft") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblprice_per_sq_ft" runat="server" Text='<%# Eval("price_per_sq_ft") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CC Price/SqFt." ItemStyle-CssClass="txtRT">
<EditItemTemplate>
<asp:TextBox ID="txtcc_price_per_sq_ft" runat="server" Text='<%# Eval("cc_price_per_sq_ft") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcc_price_per_sq_ft" runat="server" Text='<%# Eval("cc_price_per_sq_ft") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Price (in lacs)" ItemStyle-CssClass="txtRT">
<EditItemTemplate>
<asp:TextBox ID="txttotal_price" runat="server" Text='<%# Eval("total_price") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbltotal_price" runat="server" Text='<%# Eval("total_price") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="" ItemStyle-CssClass="txtLT">
<ItemTemplate>
<asp:ImageButton runat="server" ID="btnEditItem" CssClass="edBtn" ImageUrl="~/Admin/Includes/Images/edit.png"
ToolTip="Edit Item" CommandName="EditItem" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:ImageButton runat="server" ID="btnDeletetem" CssClass="edBtn" ImageUrl="~/Admin/Includes/Images/delete.png"
CommandName="DeleteItem" ToolTip="Delete Item" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>

Use the "C" parameter in the ToString function, and make sure you set the globalaztion attributes.
string parseValueIntoCurrency(double number) {
// set currency format
string curCulture = Thread.CurrentThread.CurrentCulture.ToString();
System.Globalization.NumberFormatInfo currencyFormat = new
System.Globalization.CultureInfo(curCulture).NumberFormat;
currencyFormat.CurrencyNegativePattern = 1;
return number.ToString("c", currencyFormat);
}
If you want to use a different Culture (say you're in USA, and you want the Indian format) then just use the appropriate CultureInfo element rather than getting it out of the current thread.
EXTRA INFO DUE TO OP EDIT
All right, what you're wanting to do to get this into your grid, is to create a PROTECTED function which takes in the number to be converted, and returns the converted string (this is basically the code above.
Now, on the ASPX side, you need to use that function in your grid view.
So, instead of this:
<asp:TemplateField HeaderText="Total Price (in lacs)" >
<EditItemTemplate>
<asp:TextBox ID="txttotal_price" runat="server"
Text='<%# Eval("total_price") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbltotal_price" runat="server"
Text='<%# Eval("total_price") %>'> />
</ItemTemplate>
</asp:TemplateField>
you'll use this templatefield:
<asp:TemplateField HeaderText="Total Price (in lacs)" >
<EditItemTemplate>
<asp:TextBox ID="txttotal_price" runat="server"
Text='<%# Eval("total_price") %>' />
</EditItemTemplate>
<ItemTemplate>
<%# parseValueIntoCurrency(Eval("total_price")) %>'>
</ItemTemplate>
</asp:TemplateField>
Note, two things. The first is that I'm still passing the UNFORMATTED value into the EDIT TEMPLATE, and that I'm not instantiating an extra LABEL in the ITEM TEMPLATE.
The reason I'm not doing the extra label, is because we just don't need it in there. That's just a bit more processor/memory overhead that you just don't need to incur.
As for passing the unformatted value to the text field, that's because it'll ultimately be easier to validate without having to parse out the commas and other string elements.

Related

How to delete a row from GridView without affecting the Database

I am populating a Gridview using a form with the help of AJAX.
I want to add a delete button to each row and whendelet button is clicked that row should be deleted from GridView (not hidden).
Here is my aspx code:
<asp:Content ID="Content2" ContentPlaceHolderID="Nav" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<table>
<tr>
<td class="auto-style1">
<asp:Label ID="LabelFirstName" runat="server" Text="First Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBoxFirstName" runat="server" CssClass="auto-style2"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="LabelLastName" runat="server" Text="Last Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBoxLastName" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<br /><br />
<asp:Button ID="ButtonSearch" runat="server" Text="Search" CssClass="auto-style3" Width="93px" OnClick="ButtonSearch_Click" />
<br /><br />
<asp:Label ID="LabelNoRows" runat="server" Text="Sorry, we couldn't find any data with this Name." Visible="false" ForeColor="Red"></asp:Label>
<asp:Panel ID="PanelAbsenceInfo" runat="server" Visible="false">
<table>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelFname" runat="server" Text="First Name:"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetFirstName" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelLname" runat="server" Text="Last Name"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetLname" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelEmail" runat="server" Text="Email"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetEmail" runat="server"></asp:Label>
</td>
</tr>
<asp:UpdatePanel ID="UpdatePanelInfo" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelPersonal" runat="server" Text="Personal Days Approved" ></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetPersonal" runat="server" ></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelOther" runat="server" Text="Other Days Approved"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetOther" runat="server" ></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelTotalDays" runat="server" Text="Total Days Approved" ></asp:Label>
</td>
<td>
<asp:Label ID="LabelgetTotaldays" runat="server" ></asp:Label>
</td>
</tr>
</table>
<br /><br />
<asp:GridView ID="GridViewViewAllRequests" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowCommand="GridViewViewAllRequests_RowCommand">
<Columns>
<asp:BoundField DataField="scrap" Visible ="false" />
<asp:BoundField DataField="isApproved" Visible="false" />
<asp:BoundField HeaderText="Date of Absence" DataField="requestedDate" DataFormatString="{0:MM/dd/yyyy}" />
<asp:BoundField HeaderText="Rotation Period" DataField="rotationPeriod" />
<asp:BoundField HeaderText="Reason" DataField="reason" />
<asp:BoundField HeaderText="Days Missed" DataField="daysMissed" />
<asp:BoundField HeaderText="Department" DataField="departmentName" />
<asp:BoundField HeaderText="Course" DataField="courseName" />
<asp:TemplateField HeaderText="Approved/Declined">
<ItemTemplate>
<asp:Label ID="LabelApproveorDecline" runat="server" Text='<%# Eval("isApproved") == null ? "Decision not yet made." : ((bool)Eval("isApproved") ? "Approved" : "Declined") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Scrap/Undo">
<ItemTemplate>
<asp:Button ID="ScrapButton" CommandArgument='<%# Eval("id") %>' runat="server" Text="Scrap" CommandName="Scrap" Visible='<%# !(bool)Eval("scrap") %>' />
<asp:Button ID="UndoButton" CommandArgument='<%# Eval("id") %>' runat="server" Text="Undo" CommandName="Undo" Visible='<%# (bool)Eval("scrap") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<br /><br />
</asp:Content>
And here is my cs code:
public partial class AbsenceRequestMonitor : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonSearch_Click(object sender, EventArgs e)
{
DoAction();
}
public Boolean ScraptheRequest(int id, bool action)
{
bool success = false;
success = DBOperation.ScrapAbsencedate(id, action);
return success;
}
protected void GridViewViewAllRequests_RowCommand(object sender, GridViewCommandEventArgs e)
{
//Determine the RowIndex of the Row whose Button was clicked.
int id = Convert.ToInt32(e.CommandArgument);
//Get the value of column from the DataKeys using the RowIndex.
// int id = Convert.ToInt32(GridViewViewAllRequests.DataKeys[rowIndex].Values[0]);
if(e.CommandName == "Scrap")
{
ScraptheRequest(id, true);
}
else if(e.CommandName == "Undo")
{
ScraptheRequest(id, false);
}
DoAction();
UpdatePanelInfo.Update();
}
public void DoAction()
{
string firstName = null;
string lastName = null;
firstName = TextBoxFirstName.Text.ToString();
lastName = TextBoxLastName.Text.ToString();
double PdCount = 0;
double OtherCount = 0;
if (firstName != null && lastName != null)
{
//gets student data from the Student Form
List<AbsenceMonitorData> l_studentAbsenceInfo = DBOperation.getStudentAbsenceInfo(firstName, lastName);
AbsenceMonitorData studentAbsenceInfo = l_studentAbsenceInfo.FirstOrDefault();
PdCount += l_studentAbsenceInfo.Where(x => x.reason == "Personal Day").Where(y => y.isApproved == true).Where(z => z.scrap == false).Select(a => a.daysMissed).Sum();
OtherCount += l_studentAbsenceInfo.Where(x => x.reason != "Personal Day").Where(y => y.isApproved == true).Where(z => z.scrap == false).Select(a => a.daysMissed).Sum();
GridViewViewAllRequests.DataSource = l_studentAbsenceInfo;
GridViewViewAllRequests.DataBind();
if (l_studentAbsenceInfo.Count > 0)
{
LabelGetPersonal.Text = PdCount.ToString();
LabelGetOther.Text = OtherCount.ToString();
LabelgetTotaldays.Text = (PdCount + OtherCount).ToString();
LabelGetFirstName.Text = studentAbsenceInfo.firstName.ToString();
LabelGetLname.Text = studentAbsenceInfo.lastname.ToString();
LabelGetEmail.Text = studentAbsenceInfo.studentEmail.ToString();
PanelAbsenceInfo.Visible = true;
LabelNoRows.Visible = false;
}
else
{
LabelNoRows.Visible = true;
}
}
}
}
Right now i was using the Scrap/Undo button which i want to replace it with a Delete button.
Also when i delete the row the count should be affected. (ie. Personal Days Approved, Other Days Approved and Total Days Approved)
The image shows that when i type the name and hit search, GridView is obtained.
I need to be able to delete rows from that gridview.
GridView

How to avoid a page refresh when CheckBox selected in repeater in C#?

In an asp.net web page with a repeater control, how can I avoid a complete page refresh when I select a checkbox in the header to check all checkboxes in the item template rows?
My project is based on asp.net C#, with SQL Server as database.
<asp:Repeater ID="Repeater_product_detail" runat="server" OnItemCommand="Repeater_product_detail_ItemCommand" OnItemDataBound="Repeater_product_detail_ItemDataBound">
<HeaderTemplate>
<table class="table table-striped table-bordered ">
<thead>
<tr>
<td> <asp:CheckBox ID="chk_select" AutoPostBack="true" runat="server" OnCheckedChanged="chk_select_CheckedChanged"/> </td>
<th>SubCategory</th>
<th>Product Name</th>
<th>Product image</th>
<th>Product Price</th>
<th>in stock</th>
<th>Type for</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:CheckBox ID="chkDelete" AutoPostBack="true" runat="server" />
<asp:Label ID="lbl_id" Visible="false" runat="server" Text='<%# ("int_product_id") %>'></asp:Label>
</td>
<td>
<asp:Label ID="lbl_sub_cate" runat="server" Text='<%# Eval("txt_sub_category_name") %>'></asp:Label>
<asp:DropDownList ID="ddl_sub_category" Width="100px" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "txt_sub_category_name") %>' runat="server" Visible="false" > </asp:DropDownList>
</td>
<td> <asp:Label ID="lbl_product_name" runat="server" Text='<%# Eval("txt_product_name") %>'></asp:Label>
<asp:TextBox ID="txt_product_name" BackColor="#d4d0c8" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "txt_product_name")%>' Visible="false"></asp:TextBox>
</td>
<td> <%--<asp:Label ID="lbl_product_image" runat="server" Text='<%# Eval("product_img_small") %>'></asp:Label>--%>
<asp:Image ID="Image1" Height="50px" Width="50px" ImageUrl='<%# Eval("product_img_small") %>' runat="server" />
</td>
<td> <asp:Label ID="lbl_product_price" runat="server" Text='<%# Eval("txt_product_price") %>'></asp:Label>
<asp:TextBox ID="txt_product_price" Width="60px" BackColor="#d4d0c8" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "txt_product_price")%>' Visible="false"></asp:TextBox>
</td>
<td> <asp:Label ID="lbl_stock" runat="server" Text='<%# Eval("in_stock") %>'></asp:Label>
<asp:TextBox ID="txt_stock" BackColor="#d4d0c8" Width="60px" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "in_stock")%>' Visible="false"></asp:TextBox>
</td>
<td> <asp:Label ID="lbl_type" runat="server" Text='<%# Eval("cate_type") %>'></asp:Label>
<asp:DropDownList ID="ddl_type" runat="server" Width="60px" DataTextField="cate_type" Visible="false"></asp:DropDownList>
</td>
<td>
<asp:LinkButton ID="lnk_edit" CommandArgument='<%# Eval("int_product_id") %>' CommandName="edit" runat="server">Edit</asp:LinkButton>
<asp:LinkButton ID="lnk_update" CommandArgument='<%# Eval("int_product_id") %>' Visible="false" CommandName="update" runat="server">Update</asp:LinkButton>
<asp:LinkButton ID="lnk_cancel" CommandArgument='<%# Eval("int_product_id") %>' Visible="false" CommandName="cancel" runat="server">Cancel</asp:LinkButton>
<asp:LinkButton ID="lnk_delete" CommandArgument='<%# Eval("int_product_id") %>' CommandName="delete" OnClientClick='javascript:return confirm("Are you sure you want to delete?")' runat="server">Delete</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr style="background-color:#15880a">
<td colspan="8">
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:LinkButton ID="lnk_del_selected" CommandArgument='<%# Eval("int_product_id") %>' OnClientClick='javascript:return confirm("Are you sure you want to delete?")' runat="server" OnClick="lnk_del_selected_Click">Deleted Selected</asp:LinkButton>
Behind Code
protected void chk_select_CheckedChanged(object sender, EventArgs e)
{
Control header_control = Repeater_product_detail.Controls[0].Controls[0]; // Find header Template's Items
CheckBox chk = header_control.FindControl("chk_select") as CheckBox;
if (!chk.Checked)
{
toggleCheckState(false);
}
else
{
toggleCheckState(true);
}
}
public void toggleCheckState(bool checkstate)
{
foreach (RepeaterItem item in Repeater_product_detail.Items) // Find Item Template's Items
{
if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
{
CheckBox chk_delete = (CheckBox)item.FindControl("chkDelete");
chk_delete.Checked = checkstate;
}
}
Set AutoPostBack="false" in checkbox properties.
The crux of your question, I believe, is:
"when i select any value from drop down i load some data from database that depends on this selected value, i am facing a problem whenever selection changes page will be refreshed."
There are many ways to accomplish this, but it might require some restructuring to produce the desired effect. A relatively simple way to do this would be:
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<ContentTemplate>
<asp:CheckBox ID="chk_select" AutoPostBack="true" runat="server" OnCheckedChanged="chk_select_CheckedChanged"/>
</ContentTemplate>
<Triggers>
<asp:Asyncpostbacktrigger controlid="chk_select" eventname="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
Set the AutoPostBack property to false on the checkbox.
The previous answer was almost correct, except the ASP.NET checkbox doesn't have a SelectedIndexChanged event. It should be CheckedChanged
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<ContentTemplate>
<asp:CheckBox ID="chk_select" AutoPostBack="true" runat="server" OnCheckedChanged="chk_select_CheckedChanged"/>
</ContentTemplate>
<Triggers>
<asp:Asyncpostbacktrigger controlid="chk_select" eventname="CheckedChanged" />
</Triggers>
</asp:UpdatePanel>
set value of Autopostback attribute of checkbox which causing postback to false
You can set AutoPostBack property of CheckBox to false or else you can also use Ajax UpdatePanel control and put your CheckBox inside it so that whole page will not be reloaded and only checkbox value will be refreshed.

C#,asp.net gridview ,edit a value using the radiobutton

I am using a grid in which inside the item template(the first one in which radio button is there). i use link button instead of radiobutton ,when i click on it iam able to edit as the textbox appears, but if i use the radio button,that editing option is not coming;
aspx:
<div id="loginblock">
<table>
<tr>
<td>UserName:</td>
<td>
<asp:TextBox ID="username" runat="server" onBlur="txtvalidation();" AutoPostBack="true"></asp:TextBox>
</td>
<td>
<div id="warning" style="color:aqua;width:100px" runat="server">
</div>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="PlS Enter Password" ControlToValidate="pwd"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<asp:TextBox ID="pwd" runat="server" TextMode="Password" ></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnLogin" runat="server" OnClick="btnLogin_Click" Text="Button" />
</td>
</tr>
<tr>
<asp:GridView ID="grd" runat="server" OnRowEditing="selectrd_CheckedChanged" AutoGenerateColumns="false" DataKeyNames="userid">
<Columns>
<asp:TemplateField HeaderText="edition">
<ItemTemplate>
<asp:RadioButton ID="rdnselect" runat="server" CommndName="edit" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="ids" DataField="userid" />
<asp:TemplateField HeaderText="password">
<ItemTemplate>
<%# Eval("pwd") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="edits" runat="server" Text='<%# Eval("pwd") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
cs:
protected void selectrd_CheckedChanged(object sender, GridViewEditEventArgs e)
{
grd.SelectedIndex = e.NewEditIndex;
ldgrid();
}
Here if we remove the radiobutton and insert link button,onclick of the link button we can edit the values,pls say me how to do the same operation with the radio button.

GridView: Hide Sorting Arrows on Header

I am having difficulties hiding the sorting arrows on a column header that is not sortable.
I clearly define my sortable columns in the HeaderTemplate sections, and non sortable columns in the ItemTemplate, yet the sorting arrows still appears for the second TemplateField defined below. What am i Missing?
<asp:GridView ID="gvBeneficiary" runat="server" Width="100%" AllowPaging="True" CssClass="gridheader"
EmptyDataText=""
AutoGenerateColumns="False" PageSize="10"
OnPageIndexChanging="gvBeneficiary_PageIndexChanging" OnRowCommand="gvBeneficiary_RowCommand"
OnRowDataBound="gvBeneficiary_RowDataBound" HeaderStyle-CssClass="lhs">
<Columns>
<asp:TemplateField HeaderStyle-CssClass="lhs">
<HeaderTemplate>
<asp:LinkButton ID="lnkFullName" Text="Full Name"
CommandName="Sort" CommandArgument="FullName" runat="server"></asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<%#Eval("FullName") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CommandName="EditClick" CommandArgument='<%#Eval("RecipientID") %>'
Text="Edit">
</asp:LinkButton>
<asp:LinkButton ID="lnkDelete" runat="server" CommandName="DeleteClick" CommandArgument='<%#Eval("RecipientID") %>'
Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
What do u mean by defining non sortable columns in the ItemTemplate ?
Specify Allowsorting =true for the grid asd sort expression for respective columns which u want sorting to be enabled.
<asp:GridView AllowSorting="true"......../> and
<asp:TemplateField.............. SortExpression ="Full Name">
And don't specify the sort expression for columns u don't need sorting.
I think this is enough for sorting specified columns.
Is there a reason you can't use the default sorting ability in the gridview? If you can, apply the "arrows" CSS to all hyperlinks in a table header cell
.gvclass th a {background-image...}
That way all headers with a SortExpression will have those CSS properties and all non-sortable headers will not (as no hyperlink will be generated in those cells).
If you just want to disable sorting for a specific column in an event, normally it should work to set the GridViewColumn's SortExpression to null:
gvBeneficiary.Columns[0].SortExpression = null;
I have done this using listview.Please try it with Gridview
my html code is
<asp:ListView ID="lst_Area" runat="server" ItemPlaceholderID="tr" OnItemDataBound="lst_Area_ItemDataBound">
<LayoutTemplate>
<table cellspacing="0">
<tr class="hdrRowColor1">
<td width="35px" align="left">
S.No
</td>
<td align="left" width="400px">
<asp:LinkButton ID="lnk_Name" runat="server" CommandArgument="tblAreaNew.AreaName"
ValidationGroup="vgSearch" OnClick="lnk_Sort">Name</asp:LinkButton>
<asp:Image ID="img_lnk_Name" Visible="false" runat="server" />
</td>
<td align="left" width="250px">
<asp:LinkButton ID="lnk_Location" runat="server" CommandArgument="tblAreaNew.Locationid"
ValidationGroup="vgSearch" OnClick="lnk_Sort">Location</asp:LinkButton>
<asp:Image ID="img_lnk_Location" Visible="false" runat="server" />
</td>
<td align="left" width="175px">
<asp:LinkButton ID="lnk_CreatedBy" runat="server" CommandArgument="v.FirstName" ValidationGroup="vgSearch"
OnClick="lnk_Sort">Created By</asp:LinkButton>
<asp:Image ID="img_lnk_CreatedBy" Visible="false" runat="server" />
</td>
<td align="left" width="120px">
<asp:LinkButton ID="lnk_CreatedOn" runat="server" CommandArgument="tblAreaNew.createddate"
ValidationGroup="vgSearch" OnClick="lnk_Sort">Created On</asp:LinkButton>
<asp:Image ID="img_lnk_CreatedOn" Visible="false" runat="server" />
</td>
<td align="left" width="175px">
<%--<asp:LinkButton ID="lnkCreatedDate" runat="server" CommandArgument="tblUserActivities.CreatedDate"
OnClick="lnk_Sort">Created Date</asp:LinkButton>--%>
<asp:LinkButton ID="lnk_LastModfiedBy" runat="server" CommandArgument="v.FirstName"
ValidationGroup="vgSearch" OnClick="lnk_Sort">Last Modified By</asp:LinkButton>
<asp:Image ID="img_lnk_LastModfiedBy" Visible="false" runat="server" />
</td>
<td align="left" width="120px">
<asp:LinkButton ID="lnk_LastModfiedOn" runat="server" CommandArgument="tblAreaNew.ModifiedDate"
ValidationGroup="vgSearch" OnClick="lnk_Sort">Last Modified On</asp:LinkButton>
<asp:Image ID="img_lnk_LastModfiedOn" Visible="false" runat="server" />
</td>
<td align="center" width="50px">
<asp:LinkButton ID="lnk_Status" runat="server" CommandArgument="tblAreaNew.isactive"
ValidationGroup="vgSearch" OnClick="lnk_Sort">Status</asp:LinkButton>
<asp:Image ID="img_lnk_Status" Visible="false" runat="server" />
</td>
<td align="center" width="50px" style="border-right: 1px solid #6398cc;">
Activity
<%-- <div style="width: 50px; float: right;">
</div>--%>
</td>
</tr>
<tr id="tr" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td align="left" valign="middle">
<%# Container.DataItemIndex+1 %>.
</td>
<td align="left">
<asp:Label ID="lblAreaID" runat="server" Text='<%# Eval("Areaid")%>' Visible="false"></asp:Label>
<%# Eval("AreaName")%>
</td>
<td align="left">
<%# Eval("Location")%>
</td>
<td align="left">
<%# Eval("CreatedBy")%>
</td>
<td align="left">
<%# Convert.ToDateTime(Eval("CreatedDate")).ToString("MMM, dd yyyy")%>
</td>
<td align="left">
<%# Eval("ModifiedBy")%>
</td>
<td align="left">
<%# Convert.ToDateTime(Eval("ModifiedDate")).ToString("MMM, dd yyyy")%>
</td>
<td align="center">
<asp:Label ID="lblLocationIsActive" runat="server" Style="display: none;" Text='<%# Eval("LocationIsActive")%>'></asp:Label>
<asp:Label ID="lbl_Status" runat="server" Style="display: none;" Text='<%# Eval("IsActive")%>'></asp:Label>
<asp:ImageButton ID="imgbtnStatus" runat="server" CommandArgument='<%# Eval("Areaid") %>'
OnClick="imgbtnStatus_Onclick" />
</td>
<td class="last" align="center">
<asp:Label ID="lblAreaName" runat="server" Style="display: none;" Text='<%# Eval("AreaName")%>'></asp:Label>
<asp:ImageButton ID="imgbtnEdit" runat="server" ImageUrl="~/App_Themes/ThemeNew/Images/edit.png"
ToolTip="Edit Details" CommandArgument='<%# Eval("AreaId") %>' OnClick="imgbtnEdit_OnClick" />
<asp:ImageButton ID="imgbtnDelete" runat="server" ImageUrl="~/App_Themes/ThemeNew/Images/delete.png"
ToolTip="Delete" CommandArgument='<%# Eval("AreaId") %>' Visible="false" OnClientClick="return confirm('Are you sure you want to delete the location?');"
OnClick="imgbtnDelete_OnClick" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
And my code behind code is
protected void lnk_Sort(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
string arg = lnk.CommandArgument.ToString();
ViewState["sortCol"] = arg;
GetSortDirection();
BindData(ViewState["sortCol"].ToString(), ViewState["sortDir"].ToString(), Convert.ToInt32(ViewState["nmbr"]), Pager.PageSize);
string name = lnk.ID;
Image img = (Image)(lst_Area.FindControl("img_" + name));
if (img != null)
{
SetSortOrderImage(img, ViewState["sortDir"].ToString());
}
}
private void SetSortOrderImage(Image image, String sortorder)
{
if (sortorder == "asc")
{
image.Visible = true;
image.ImageUrl = "../App_Themes/ThemeNew2/images/up.png";
}
else if (sortorder == "Desc")
{
image.Visible = true;
image.ImageUrl = "../App_Themes/ThemeNew2/images/down.png";
}
}
/// <summary>
/// this method get the sort direction
/// </summary>
private void GetSortDirection()
{
if (Convert.ToString(ViewState["sortDir"]) == "Desc")
{
ViewState["sortDir"] = "asc";
}
else
{
ViewState["sortDir"] = "Desc";
}
}
Hope this will work for you.one this more i would like to let you know the inbuilt sorting and paging are slower for gridview as compare to custom paging and sorting.

How can i have a gridview or details view in a popup

This is my design
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Font-Names="Arial"
Font-Size="11pt" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"
CellPadding="4" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="CheckAll" onclick="return check_uncheck (this );" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="ID" Visible="false" Text='<%# DataBinder.Eval (Container.DataItem, "Id") %>'
runat="server" />
<asp:CheckBox ID="deleteRec" onclick="return check_uncheck (this );" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Id" SortExpression="Id">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FileName" SortExpression="FileName">
<EditItemTemplate>
<asp:Label ID="LblFileName" runat="server" Text='<%# Eval("FileName") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LblFileName1" runat="server" Text='<%# Bind("FileName") %>'></asp:Label>
<asp:ImageButton ID="img" runat="Server" CommandName="Image" ImageUrl="~/Images/pen.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<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" />
</asp:GridView>
<asp:Panel ID="pnlAddEdit" runat="server" CssClass="modalPopup" Style="display: none"
Width="1000px">
<asp:Label Font-Bold="true" ID="Label4" runat="server" Text="File Data"></asp:Label>
<br />
<table align="center" width="1000px">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="RecordTypeCode"></asp:Label>
</td>
<td>
<asp:Label ID="lblRec" runat="server" Text="Content"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblFileHeader" runat="server" Text="FileHeader"></asp:Label>
</td>
<td>
<asp:Label ID="txtCustomerID" Width="500px" MaxLength="5" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblBatchHeader" runat="server" Text="BatchHeader"></asp:Label>
</td>
<td>
<asp:Label ID="txtBatch" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text="EntryDetail"></asp:Label>
</td>
<td>
<asp:Label ID="txtEntry" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" />
</td>
<td>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClientClick="return Hidepopup()" />
</td>
</tr>
</table>
</asp:Panel>
<asp:LinkButton ID="lnkFake" runat="server"></asp:LinkButton>
<cc1:ModalPopupExtender ID="popup" runat="server" DropShadow="false" PopupControlID="pnlAddEdit"
TargetControlID="lnkFake" BackgroundCssClass="modalBackground">
</cc1:ModalPopupExtender>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" />
<asp:AsyncPostBackTrigger ControlID="btnSave" />
</Triggers>
</asp:UpdatePanel>
I have taken some text boxes inside a panel when a pop-up opens but instead of that i need a gridview to be there as i have to display the content of a large file
This is my data
101 111100022 5104885671104200936A094101CapitalOne MudiamInc
5220MudiamInc A510488567CCDITServices000000110422 1111100020000001
622968765348545646565 00004000001007 rajeshk 1111100020000001
62297877654775676546546 00002888891007 rajeshk 1111100020000002
82200000020194754188000000000000000000688889A510488567 111100020000001
5220MudiamInc A510488567CCDITServices000000110422 1111100020000002
62212345678034354465677 00000864451005 swethau 1111100020000003
62212345678087664534543 00000559841011 swathiK 1111100020000004
62212345678097867546435 00000579351012 lavanyaK 1111100020000005
6221234567806754654435435 00000846761013 AnithaN 1111100020000006
82200000040049382712000000000000000000285040A510488567 111100020000002
9000002000001000000060244136900000000000000000071739300
This i have to show sequentially in an order as
RecordTyecode Content
FileHeader Starting line to be here
BatchHeader Line that come's with 5(First come line)
EntryDetail Number of 6 line has to be added on by one
BatchControl line that starts with 8 has to be here
Again if i have line starts with 5 after 8 that has to be appended like above sequence
Can any give me an idea to add this dynamically a little tricky to understand ask if any information required
This was done in winforms exact i need in web too
Just in a simple way i get this answer
Declared a hash table
static Hashtable rectype = new Hashtable();
In page load i add the following
if (rectype != null)
{
rectype.Add("1", "File Header");
rectype.Add("5", "Batch Header");
rectype.Add("6", "Entry Detail");
rectype.Add("7", "Addenda Record");
rectype.Add("8", "Batch Control");
rectype.Add("9", "File Control");
}
Here is my code when user clicks on Image button
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int id = 0;
string strLine = string.Empty;
string[] lines = null;
if (e.CommandName == "Image")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
Label l = (Label)GridView1.Rows[row.RowIndex].Cells[1].FindControl("Label1");
id = Convert.ToInt16(l.Text);
string selectSQL = "Select File_Data from tblachmaster WHERE Id IN (" + id + ")";
MySqlCommand cmd1 = new MySqlCommand(selectSQL);
cmd1.Parameters.Add("#_id", SqlDbType.Int).Value = id;
DataTable dt1 = GetData1(cmd1);
if (dt1 != null)
{
for (int i = 0; i < dt1.Rows.Count; i++)
{
Byte[] bytes = (Byte[])dt1.Rows[i]["File_Data"];
string text = Encoding.UTF8.GetString(bytes);
lines = Regex.Split(text, "\r\n");
strLine = convertArrayToString(lines);
}
}
DataTable table = new DataTable();
table.Columns.Add("RecordTypeCode", typeof(string));
table.Columns.Add("Content", typeof(string));
foreach (string strcontent in lines)
{
if (strcontent != string.Empty)
table.Rows.Add(rectype[(strcontent.Substring(0, 1))], strcontent);
}
dynamicGridView.DataSource = table;
dynamicGridView.DataBind();
popup.Show();
}
}
This works well for me and here is my output after clicking on Image button
You can use Ajax pop up control similar to this -
http://www.ezzylearning.com/tutorial.aspx?tid=2861497

Categories