i have created a telerik grid for small payment module
in this module i have selected two checkbox and enter a amount,i need the total amount to be displayed in the donation amount label
The current code is to sum up the values displayed in the second column,and saving the values in session and passsing to next page.
Gridview
<telerik:GridTemplateColumn FilterControlAltText="Filter TemplateColumn3 column" UniqueName="TemplateColumn3">
<ItemTemplate>
<asp:TextBox ID="txt_amnt" runat="server"></asp:TextBox> </td>
</ItemTemplate>
</telerik:GridTemplateColumn>
c# code
protected void chk_box_CheckedChanged(object sender, EventArgs e)
{
if (ViewState["dt"].ToString().Trim() != "NULL")
{
dt = (DataTable)ViewState["dt"];
}
if (dt.Columns.Count == 0)
{
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Amount");
}
CheckBox chk = (CheckBox)sender;
if (chk.Checked == true)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count-1 ]["Id"] = ((Label)chk.FindControl("lb_id")).Text.Trim();
dt.Rows[dt.Rows.Count - 1]["Name"] = ((Label)chk.FindControl("lb_donation")).Text.Trim();
dt.Rows[dt.Rows.Count - 1]["Amount"] = ((Label)chk.FindControl("lb_amount")).Text.Trim();
// dt.Rows[dt.Rows.Count + 1]["chkstatus"] = ((Label)chk.FindControl("lb_amount")).ToString().Trim();
}
else {
for (int i = 0; i < dt.Rows.Count; i++)
{
if(((Label)chk.FindControl("lb_id")).Text.Trim()==dt.Rows[i]["Id"].ToString().Trim())
{ dt.Rows.RemoveAt(i); }
}
}
ViewState["dt"] = dt;
double tamount = 0;
for (int i2 = 0; i2 < dt.Rows.Count; i2++)
{
tamount = tamount + Convert.ToDouble(dt.Rows[i2]["Amount"]);
}
lb_tamount.Text = tamount.ToString() ;
}
I believe your code for the CheckBox will always hit error.
How can you find a control inside a CheckBox ? Secondly your code is not complete as per the result you are showing. Anyway here is the idea how you can get checked item in your RadGrid.
First you need loop the RadGrid to get all checked CheckBox.
Then sum up the total and put it to the label.
This code just to mock up for your scenario. Please use TryParse to get the int value to ensure no converting error.
Code Behind
protected void chkCheck_CheckedChanged(object sender, EventArgs e)
{
// Variable
int total = 0;
int amt = 0;
int donateAmt = 0;
foreach (GridDataItem item in rg.Items)
{
// Find Control
CheckBox chkCheck = item.FindControl("chkCheck") as CheckBox;
Label lblAmount = item.FindControl("lblAmount") as Label;
TextBox txtAmount = item.FindControl("txtAmount") as TextBox;
// Reset Amount
amt = 0;
donateAmt = 0;
// Check
if (chkCheck != null && chkCheck.Checked)
{
// Check & Get Value
if (lblAmount != null && txtAmount != null)
{
// Check & Set
if (lblAmount.Text.Trim() != string.Empty)
amt = Convert.ToInt32(lblAmount.Text.Trim());
// Check & Set
if (txtAmount.Text != string.Empty)
donateAmt = Convert.ToInt32(txtAmount.Text.Trim());
// Check current Amount in stock and donate amt
if (donateAmt > amt)
{
donateAmt = amt;
txtAmount.Text = donateAmt + "";
}
// Reset to the text
}
total += donateAmt;
}
}
lblTotal.Text = total + "";
}
Related
Currently I try to use Repeater WebControl in order to display a table that list out all possible component. Below is my table;
Right now I try to merged cells in Group Code and Group Description column that have the same value. Below is my merging cell code, noted that the code is in class;
public void repeaterRowSpan(string repeaterID, string columnID)
{
var pageHandler = HttpContext.Current.CurrentHandler;
Control ctrl = ((Page)pageHandler).Master.FindControl("ContentPlaceHolder3").FindControl(repeaterID);
Repeater repeaterName = (Repeater)ctrl;
for (int i = repeaterName.Items.Count - 1; i > 0; i--)
{
HtmlTableCell oCell_previous = (HtmlTableCell)repeaterName.Items[i - 1].FindControl(columnID);
HtmlTableCell oCell = (HtmlTableCell)repeaterName.Items[i].FindControl(columnID);
oCell.RowSpan = (oCell.RowSpan == -1) ? 1 : oCell.RowSpan;
oCell_previous.RowSpan = (oCell_previous.RowSpan == -1) ? 1 : oCell_previous.RowSpan;
if (oCell.InnerText == oCell_previous.InnerText)
{
oCell.InnerText = "";
oCell_previous.RowSpan += oCell.RowSpan;
}
}
}
Somehow the code manage to delete the same value in the column but maintain the rowspan. When I debugged, the oCell_previous.RowSpan return '2' so the code itself working fine. Below is the result of merging;
How can I modified my code in such way it will merged the cell?
In your opinion, between Repeater and GridView which is most suitable to show data in table form in this project? In my understanding, Repeater is most suitable since it faster than GridView. GridView is only suitable if you have edit function to go with your table.
This can be implemented using the OnDataBound event. The OnDataBound event of the GridView is executed after the GridView is populated with the records. Executed a loop in reverse over the GridView Rows and then the common Cells are identified and merged into single cell.
Below sample code merges the first & second columns (assuming that there are redundant values by comparing the above row(s)),
Feel free to leave a comment if you need more info.
protected void OnDataBound(object sender, EventArgs e)
{
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1];
for (int j = 0; j < row.Cells.Count; j++)
{
if (row.Cells[j].Text == previousRow.Cells[j].Text)
{
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
}
}
}
I have a gridview control on my form.Its first column is checkboxcolumn and the other one textboxcolumn.I am populating Textbox columns with some string values coming from list
like this way
for (int i = 0; i < listeList.Count; i++)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[1].Value = listeList[i];
}
What am i trying to do is to select all the checboxes in the gridview once the user click button How can I do this
Here is what I have tried
private void btnselectAll_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
// row.Cells[0].Value = "true";
//if (row.Cells[0].Value != ull)
//{
// if (Convert.ToBoolean(row.Cells[0].Value))
// {
// MessageBox.Show(row.Cells[1].Value.ToString());
// }
//}
}
}
Cast the appropriate cell to DataGridViewCheckBoxCell:
for(int row = 0; row < this.dataGridView1.Rows.Count; row++)
{
var chkCell = dataGridView1[0, row] as DataGridViewCheckBoxCell;
// read:
bool isChecked = (bool)chkCell.EditedFormattedValue;
// assign:
chkCell.Value = true;
}
I have a "time duration" column in a grid view, and I wish to sum that particular column in C# and publish the total time taken at a label named Total Time. How can I do this?
Sample code:
int sum = 0;
for (int i = 0; i < dgTestSteps.SelectedColumns.Count; ++i)
{
sum += Convert.ToInt32(dgTestSteps.SelectedColumns.Count.ToString());
//sum += Convert.ToInt32(dgTestSteps.Rows[i].Cells[1].Value);
}
lblTotalTime.Text = sum.ToString();
int sum = 0;
for (int i = 0; i < dgTestSteps.Rows.Count; ++i)
{
sum += Int.Parse(dgTestSteps.Rows[i].Cells[1].Value.ToString());
}
lblTotalTime.Text = sum.To String();
It seems true! Is there any problem with this?
I do this by aggregating the column row values in a class variable thusly:
Code behind:
protected void ItemsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get the row variable values
var rowView = (DataRowView)e.Row.DataItem;
var itemId = Convert.ToInt32(rowView["ItemID"]);
var skuId = Convert.ToInt32(rowView["ItemSkuID"]);
var quantity = Convert.ToInt32(rowView["Quantity"]);
// Instantiate instances of the relevant classes
var item = new Item(itemId);
var sku = new Sku(skuId);
var itemPrice = String.Format("{0:n2}", (item.Price + sku.PriceAdj));
var itemPriceLiteral = (Literal)e.Row.FindControl("ItemPrice");
if (itemPriceLiteral != null)
{
itemPriceLiteral.Text = itemPrice;
}
var itemExtendedPriceLiteral = (Literal)e.Row.FindControl("ItemExtendedPrice");
if (itemExtendedPriceLiteral != null)
{
var extendedPrice = price * quantity;
itemExtendedPriceLiteral.Text = String.Format("{0:n2}", extendedPrice);
// Increment the extended price
_totalExtendedPrice += extendedPrice;
}
}
}
// Lots of stuff omitted from this method for clarity
public void GetSummary()
{
// Set the text property of the total literal below the GridView
OrderTotal.Text = string.Format((HttpUtility.HtmlDecode(
(string)GetGlobalResourceObject("ShopStrings", "UsdPrice"))),
_totalExtendedPrice);
}
OrderTotal.Text is localized but you can easily format it without using resources.
You can use this but you should know that number of columns start with 0 and goes up with 1
int sum = 0;
for (int i = 0; i < dgTestSteps.Rows.Count; ++i)
{
sum += Convert.ToInt32(dgTestSteps.Rows[i].Cells[0].Value);
}
lblTotalTime.Text = sum.ToString();
I tried this and has no problem
I have been saving into the ComboBox a value out of the selected column in datagridview with below code.
My question is:How can I prevent duplicate records when I save the values into the ComboBox? How can I do that?
Code:
int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;
CmbAra.Text = "";
for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
{
CmbAra.Items.Add(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString());
}
Please try this
private void dgvServerList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex == 1)
{
string id = dgvServerList[e.ColumnIndex, e.RowIndex].Value.ToString();
int duplicaterow = 0;
for (int row = 0; row < dgvServerList.Rows.Count; row++)
{
if (row != e.RowIndex && id == dgvServerList[e.ColumnIndex, row].Value.ToString())
{
duplicaterow = row + 1;
MessageBox.Show("Duplicate found in the row: " + duplicaterow);
this.dgvServerList[e.ColumnIndex, e.RowIndex].Value = "";
break;
}
}
}
}
catch
{
}
}
you could first transfer your datagridview items to a dictionary (which guarantees uniqueness) and then transfer that dictionary content to the combobox. or you could check for uniqueness yourself using a 'Contains' method on the combobox. you could even tie the dictionary to the combobox as a source for the combobox items.
Dictionary<string,bool> d = new Dictionary<string,bool>();
int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;
CmbAra.Text = "";
for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
{
d[dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString()] = true;
}
CmbAra.Items.AddRange(d.Keys);
Use a set:
int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;
CmbAra.Text = "";
HashSet<string> set = new HashSet<string>();
for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
{
string s = dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString();
if(!set.Contains(s)) {
CmbAra.Items.Add(s);
set.Add(s);
}
}
by using the following check and then determine to add or not
if(CmbAra.Items.Contains(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString()))
You can use the following code part.
if(!(CmbAra.Items.Contains(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString())))
{
CmbAra.Items.Add(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString());
}
else
{
MessageBox.Show("Value Already exists , not added");
}
i have a gridview
' />
Total
my code behind :
protected void btnGetTotal_Click(object sender, EventArgs e)
{
int Rowindex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrenttable = (DataTable)ViewState["CurrentTable"];
if (dtCurrenttable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrenttable.Rows.Count; i++)
{
TextBox txtFeesAmount = (TextBox)gvSales.Rows[Rowindex].Cells[1].FindControl("txtAmount");
Total += Convert.ToInt32( txtFeesAmount.Text);
tostring= Total.ToString();
tostring = ((TextBox)gvSales.FooterRow.FindControl("txtTotal")).Text;
}
}
}
}
The values in the taxtbox are added and while display in footer template it is not assinging with the added value.
it gives me error:
object referrence not set to instance of object.
How to assign the value(total values added from each textbox) to the'txtTotal' Textbox in gridview
i.e in this line
tostring = ((TextBox)gvSales.FooterRow.FindControl("txtTotal")).Text;
do like this :
grdList.Columns[2].FooterText = sumDebit.ToString();