Modifying numbers in a List - c#

I have a variable prix that returns 5998 7510 8144 9458 10916 13214 and this list must be changed to 59,98 75,10 81,44 94,58 109,16 132,14
How can I do it. That is, add a , before the last 2 digits (from right) of each number ?
This is the C# code I've tried so far :
XDocument docxx = XDocument.Parse(Session["xmlrs" + z + ""].ToString());
//This now holds the set of all elements named field
try
{
XNamespace foobar = "http://www.april-technologies.com";
var prix = docxx.Descendants(foobar + "CotisationMensuelle").Select(x => new { CotisationMensuelle =(string)x}).ToList();
rpMyRepeater1.DataSource = prix;
rpMyRepeater1.DataBind();
}
catch(Exception ex) {}
and the C# Code is :
<asp:Repeater ID="rpMyRepeater1" ItemType="" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "CotisationMensuelle").ToString() %>
<br />
</ItemTemplate>
</asp:Repeater>

Not quite clear what you are asking as you code sample is unrelated to the list you have given as an eample. If you need to add a comma two letters from the end, try this,
string val = "7958";
string newVal = val.Insert(val.Length-2,",");
Console.WriteLine(newVal);

Try following:
XNamespace foobar = "http://www.april-technologies.com";
var prix = docxx.Descendants(foobar + "CotisationMensuelle").Select(x => new { CotisationMensuelle =(string)x}).ToList();
var newPrix = new List<string>();
foreach (var s in prix)
{
var s1 = s.CotisationMensuelle.Substring(0, s.CotisationMensuelle.Length - 2);
var s2 = s.CotisationMensuelle.Substring(s.CotisationMensuelle.Length - 2);
//add a comma before the last 2 digits (from right)
var s_total = s1 +","+ s2;
newPrix.Add(s_total);
}
rpMyRepeater1.DataSource = newPrix.Select(x => new {CotisationMensuelle = x}).ToList();
rpMyRepeater1.DataBind();

You could use DataBound event, for sample, in your page:
<asp:Repeater ID="rpMyRepeater1" ItemType="" runat="server" OnItemDataBound="rpMyRepeater1_ItemDataBound">
<ItemTemplate>
<asp:Literal ID="ltl" runat="server"></asp:Literal>
</ItemTemplate>
</asp:Repeater>
in your code behine:
int i = 0;
protected void rpMyRepeater1_ItemDataBound(object Sender, RepeaterItemEventArgs e)
{
// if the item on repeater is a item of data
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// get value
string value = DataBinder.Eval(e.Item.DataItem, "CotisationMensuelle").ToString();
// find literal
Literal ltl = (Literal)e.Item.FindControl("ltl");
// check if i < 2
if (i < 2)
{
// write value
ltl.Text = value;
//increase i
i++;
}
else
{
// write value and <br/>
ltl.Text = string.Format("{0}<br />", value);
// zero i
i = 0;
}
}
}

how about:
string data = "5998 7510 8144 9458 10916 13214";
string newValue = string.Join(" ",
from s in data.Split(' ')
select (double.Parse(s) / 100).ToString("0.00"));
//59,98 75,10 81,44 94,58 109,16 132,14

Related

How to put multiple images control in array or list in c#?

I have 60 images control of . I have two requirements:
put all images control in array
I have an roll no of 6 digits. and I want to match first digit to index of first 10 Images control, then 2nd digit to next 10 images and so on...
following is my code:
protected void Page_Load(object sender, EventArgs e)
{
//for roll no
int rollNo = int.Parse(Request.QueryString["RollNo"]);
var rollNoArray = rollNo.ToString().Select(t =>
int.Parse(t.ToString())).ToArray();
int index1=0;
int index2=0, index3=0, index4 = 0
,index5 = 0, index6 = 0;
for (int i = 0; i < rollNoArray.Length; i++)
{
//Response.Write(rollNoArray[i]+"<br>");
LBLRollNo.Text += " " +
rollNoArray[i].ToString();
if (i == 0)
{
index1 = rollNoArray[0];
}
if (i == 1)
{
index2 = rollNoArray[1];
}
if (i == 2)
{
index3 = rollNoArray[2];
}
if (i == 3)
{
index4 = rollNoArray[3];
}
if (i == 4)
{
index5 = rollNoArray[4];
}
if (i == 5)
{
index6 = rollNoArray[5];
}
}
Response.Write(index1);
//index
matchBubbles(index1);
}
}
public void matchBubbles(int index)
{
Image[] a =new Image[10];
for (int i = 0; i < 10; i++)
{
a[0] = Image0;
a[1] = Image1;
a[2] = Image2;
a[3] = Image3;
a[4] = Image4;
a[5] = Image5;
a[6] = Image6;
a[7] = Image7;
a[8] = Image8;
a[9] = Image9;
if (index == a[i])
{
}
}
}
I want to manipulate the psd file in a way that Whatever rollno is return from previous .aspx page an image(in my folder) should be inserted in the exact place against the index of the roll no means there is 10 boxes below for every digit and I want to insert the image there according to each digit of the roll no. Please help me!
Help me Please
In such case, you can do it simple way.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Check Roll No query string cannot be null
if (Request["RollNo"] != null)
{
//Check Roll No cannot exeed 6 digits
if (Request["RollNo"].Length <= 6)
{
string RollNo = Request["RollNo"];
//Check Roll No. must be all digits
int iRollNo;
if (Int32.TryParse(RollNo, out iRollNo))
{
//Prefix with zero for RollNo less than 6 digits
if (RollNo.Length < 6)
{
RollNo = new String('0', 6 - RollNo.Length) + RollNo;
}
//Display 6 images
Image1.ImageUrl = "~/Number/" + RollNo[0] + ".png";
Image2.ImageUrl = "~/Number/" + RollNo[1] + ".png";
Image3.ImageUrl = "~/Number/" + RollNo[2] + ".png";
Image4.ImageUrl = "~/Number/" + RollNo[3] + ".png";
Image5.ImageUrl = "~/Number/" + RollNo[4] + ".png";
Image6.ImageUrl = "~/Number/" + RollNo[5] + ".png";
}
}
}
}
}
Result
if RollNo. not all digits or more than 6 digits, not display
if RollNo. less than 6 digits, prefix with zero
Here's a suggestion that also comes with a lot of other tips:
Assuming you have a webforms project, enter this into your default.aspx file (not the default.aspx.cs) If you have all this happening in another file, well then you insert it all into that particular one:
<asp:Panel ID="HeaderPanel" runat="server">
<h1>Enter image roll sequence here</h1>
<asp:TextBox ID="RollNo" runat="server" Text="012345"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="send" OnClick="Button1_Click" />
<asp:Label ID="LBLRollNo" runat="server" Text="Text coming in from QueryString will end up here after postback"></asp:Label>
</asp:Panel>
<asp:Panel ID="ImagePanel" runat="server">
</asp:Panel>
Then you can paste this into your default.aspx.cs file (or whatever name you use instead:
protected void Page_Load(object sender, EventArgs e)
{
// This happens whenever there is a rollno variable coming in from the querystring
if (Request.QueryString["RollNo"] != null)
{
string RollNo = Request.QueryString["RollNo"];
ShowImages(RollNo);
}
}
// this happens when you enter the roll numbers in the text box and hit the send button
protected void Button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(RollNo.Text))
{
LBLRollNo.Text = " Selected roll numbers" + RollNo.Text;
ShowImages(RollNo.Text);
}
}
// Roll variable is the roll number. Imageno is the image number inside each Roll. And this information is stored in the image ID attribute.
protected void ShowImages(string RollNumbers)
{
LBLRollNo.Text = " Selected roll numbers" + RollNumbers;
var rollNoArray = RollNumbers.Select(t => int.Parse(t.ToString())).ToArray();
foreach (int rollno in rollNoArray)
{
// add a HTML newline, just to make it more neat
Literal templiteral = new Literal();
templiteral.Text = "<br/>";
ImagePanel.Controls.Add(templiteral);
Label templabel = new Label();
templabel.Text = "Images in roll number " + rollno.ToString();
ImagePanel.Controls.Add(templabel);
// Lay out the images belonging to this roll number (rollno)
for (int Imageno = 0; Imageno <= 5; Imageno++)
{
string identity = "ident|" + rollno.ToString() + "|" + Imageno.ToString() + "|"; // The IDs of each image on-screen will bear an ID like this: ident|0_0|
Image tempimage = new Image();
tempimage.ID = identity;
ImagePanel.Controls.Add(tempimage);
}
}
}
// This routine lays out all rolls and images in one go
protected void LayOutImages()
{
for (int Roll = 0; Roll <= 10; Roll++)
{
Label templabel = new Label();
templabel.Text = "Roll number " + Roll.ToString();
ImagePanel.Controls.Add(templabel);
for (int Imageno = 0; Imageno <= 5; Imageno++)
{
string identity = "ident|" + Roll.ToString() + "|" + Imageno.ToString() + "|"; // The IDs of each image on-screen will bear an ID like this: ident|0_0|
Image tempimage = new Image();
tempimage.ID = identity;
ImagePanel.Controls.Add(tempimage);
}
Literal templiteral = new Literal();
templiteral.Text = "<br/>";
ImagePanel.Controls.Add(templiteral);
}
}
Run it and observe that you do not need an array of image controls. You can either enter a variable in the querystring, or you can set the roll numbers in the text box. By the way. When parsing a string array starting wqith 0 from the querystring, the leading zero will not be considered, but it is fixed in this one.
The idea is that each image has an identity telling you what roll number it belongs to and what image number the image has in any given roll
Hope this helps

c# asp.net for append int value to the label id

I have the following label with ids:
<asp:Label ID="FromName0" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName1" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName2" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName3" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName4" runat="server" Visible="true"></asp:Label>
I want to assign the values to the label ids using for loop.
I am using the following tags in c#:
for (int i = 0; i < count; i++)
{
var label = this.Controls.Find("FromName " + i, true) as Label;
label.Text = Session["DeliverAddress" + i].ToString();
}
But ‘Find’ shows error like below:
System.Web.UI.ControlCollections does not have the definition for ‘Find’. But I have already added ‘System.Web.UI’ dll file. Can anyone help me?
I am using dotnet framework 4.0.
Thanks in Advance.
You can do this like this
public Control[] FlattenHierachy(Control root)
{
List<Control> list = new List<Control>();
list.Add(root);
if (root.HasControls())
{
foreach (Control control in root.Controls)
{
list.AddRange(FlattenHierachy(control));
}
}
return list.ToArray();
}
and
protected void Page_Load(object sender, EventArgs e)
{
Control[] allControls = FlattenHierachy(Page);
foreach (Control control in allControls)
{
Label lbl = control as Label;
if (lbl != null && lbl.ID == "FromName0")
{
lbl.ID = "myid";//Do your like stuff
}
}
}
Just use : Here MSDN article about FindControl
//
// Summary:
// Searches the page naming container for a server control with the specified identifier.
//
// Parameters:
// id:
// The identifier for the control to be found.
//
// Returns:
// The specified control, or null if the specified control does not exist.
public override Control FindControl(string id);
Here how your code should look like. Just as advice check if the control is null or the session variable is null, this can give you an exception.
for (int i = 0; i < count; i++)
{
var label = FindControl("FromName " + i) as Label;
if(label == null || Session["DeliverAddress" + i] == null)
continue;
label.Text = Session["DeliverAddress" + i].ToString();
}

asp.net content lost in dynamically generated table

I'm trying to use an ajax panel to add keep multiple images added to table cells dynamically. Thing is when I add the second image, the first one dissapears.
Its really just a silly example to try and get ajax controls working for another project.
I'm putting an image of Bill Gates in row 3, column 3 and an image of Steve Jobs in row 1, column 5. I have a button to place each image.
I can't seem to get both to display at the same time.
I have written a function to generate the cell id (GenerateTableCellID), as I've been told I would need to to this. Also there is a function to extract the cell and row in a tuple (GetColumnAndRow).
I'm not sure how to use a Session object to save the data. I thought using AJAX would be the answer, though I think I'm missing a major aspect of it.
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div id="tablePlaceHolder" runat="server"></div>
<asp:Button ID="tblButton2" runat="server" Text="Add Steve Jobs" OnClick="tblButton_Click_Jobs" />
<asp:Button ID="tblButton" runat="server" Text="Add Bill Gates" OnClick="tblButton_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
int tableSize = 5;
var t = new HtmlTable();
t.ID = "myTable";
var placeHolderURL = "http://wiki.tripwireinteractive.com/images/4/47/Placeholder.png";
for (int r = 0; r < tableSize; r++)
{
var tableRow = new HtmlTableRow();
tableRow.ID = "row_" + r.ToString();
for (int c = 0; c < tableSize; c++)
{
var tableCell = new HtmlTableCell();
var id = GenerateTableCellID(r, c);
tableCell.ID = id;
tableCell.Height = "20";
tableCell.Width = "20";
tableCell.InnerHtml = string.Format("<img src='{0}' width='20' height='20' />", placeHolderURL);
tableRow.Controls.Add(tableCell);
}
t.Controls.Add(tableRow);
}
tablePlaceHolder.Controls.Add(t);
}
protected void tblButton_Click(object sender, EventArgs e)
{
int c =2;
int r = 2;
var id = GenerateTableCellID(c, r);
var image = GenerateImage("http://www.mnn.com/sites/default/files/billgates.jpg");
var cell = (HtmlTableCell)UpdatePanel2.FindControl(id);
cell.InnerHtml = "";
cell.Controls.Add(image);
}
protected void tblButton_Click_Jobs(object sender, EventArgs e)
{
int c = 4;
int r = 0;
var id = GenerateTableCellID(c, r);
var image = GenerateImage("http://images.boomsbeat.com/data/images/full/209/jobs-jpg.jpg");
var cell = (HtmlTableCell)UpdatePanel2.FindControl(id);
cell.InnerHtml = "";
cell.Controls.Add(image);
}
protected Image GenerateImage(string url)
{
var image = new Image();
image.ImageUrl = url;
image.Width = 20;
image.Height = 20;
return image;
}
protected string GenerateTableCellID(int c, int r)
{
return "column_" + c.ToString() + "_row_" + r.ToString();
}
protected Tuple<int, int> GetColumnAndRow(string tableCellID)
{
string[] splitString = tableCellID.Split('_');
int column, row;
if (Int32.TryParse(splitString[1], out column) && Int32.TryParse(splitString[3], out row))
{
return new Tuple<int, int>(column, row);
}
else
{
return null;
}
}
It is because at every update you clear the html present before by cell.InnerHtml = ""; remove this and try
protected void tblButton_Click_Jobs(object sender, EventArgs e)
{
int c = 4;
int r = 0;
var id = GenerateTableCellID(c, r);
var image = GenerateImage("http://images.boomsbeat.com/data/images/full/209/jobs-jpg.jpg");
var cell = (HtmlTableCell)UpdatePanel2.FindControl(id);
//cell.InnerHtml = "";
cell.Controls.Add(image);
}
As mentioned on the Page LifyCycle your table is created everytime when you do reload page (does not matter is this postback or not). Also you could read this post. In other words, it is not proper way store your data in the dynamic generated controls, because you lose your data on page load.
But if it is necessary for you could use AJAX methods ($.get and $.post, not UpdatePanel) to get data from the backend and add this to generated control on the client side

C# Trying to compare lines of a textbox and count the quantities for (sometimes duplicate) lines with different quantities

I'm still new to programming and have been creating some tools for my associates at work for some redundant tasks. As I said in the title, I would like to do something like this:
Textbox1 may have:
Apples 3
Apples 4
Oranges 1
I'd like to transfer this over to textbox 2 as this:
Apples 7
Oranges 1
It took into consideration that apples appeared twice and added the total. The code I have so far is not workingenter code here and I've been struggling with this for some time:
{
foreach (var lines in textBox1.Lines)
{
string line = lines.TrimEnd();
if (line.Length > 0)
{
int findIndex = line.LastIndexOf(" ") + 1;
var qty = (line.Substring(findIndex));
int lineInt;
try
{
lineInt = Convert.ToInt32(qty); //convert whatever the qty detected was, to int32
{
textBox2.Text += line + lineInt+Environment.NewLine.ToString();
}
}
catch (Exception)
{
}
}
}
}
The result is:
Apples 33
Apples 44
Oranges 11
Which is wrong because I am not removing the initial quantity field at the end, and I am also not totaling the integer value correctly to put on the end, I am just reattaching the quantity on the end. My end goal is to have a list of many different products/quantities and total them up and see what quantities may have changed from previous orders by doing a set difference/delta or something like that, which I can't do until I can get the right data into textbox2. The tricky part for me is merging duplicate lines of products but still adding up their combined quantity. Any insight would be greatly appreciated, thanks for reading!
Try this
ASPX
<asp:Panel ID=pnl1 runat=server>
<asp:TextBox ID=TextBox1 runat=server></asp:TextBox>
<asp:TextBox ID=TextBox2 runat=server></asp:TextBox>
<asp:TextBox ID=TextBox3 runat=server></asp:TextBox>
<asp:TextBox ID=TextBox4 runat=server></asp:TextBox>
<asp:TextBox ID=TextBox5 runat=server></asp:TextBox>
<asp:TextBox ID=TextBox6 runat=server></asp:TextBox>
</asp:Panel>
<br />
Total
<asp:Panel ID=Panel1 runat=server>
</asp:Panel>
<asp:Button ID=btn runat=server Text=Total onclick="btn_Click" />
CS. Side
protected void btn_Click(object sender, EventArgs e)
{
Dictionary<string, int> obj = new Dictionary<string, int>();
foreach (Control cn in pnl1.Controls)
{
if (cn.GetType() == typeof(TextBox))
{
if (((TextBox)cn).Text.Trim() != "")
{
string[] spValue = ((TextBox)cn).Text.Split(' ');
if (obj.ContainsKey(spValue[0]))
{
obj[spValue[0]] = obj[spValue[0]] + Convert.ToInt32(spValue[1]);
}
else
{
obj.Add(spValue[0], Convert.ToInt32(spValue[1]));
}
}
}
}
foreach (string k in obj.Keys)
{
TextBox tx = new TextBox();
tx.Text = k + " " + obj[k].ToString();
pnl1.Controls.Add(tx);
}
}
string previousLine = "";
foreach (var lines in textBox1.Lines)
{
string line = lines.TrimEnd();
if (line.Length > 0 && previousLine != "")
{
int findIndex = line.LastIndexOf(" ") + 1;
//check to ensure the item in this line is equal to the item in the previous line
if(line.substring(0, findIndex - 2) == previousLine.substring(0, findIndex - 2))
{
var qty = (line.Substring(findIndex));
int lineInt;
try
{
lineInt = Convert.ToInt32(qty); //convert whatever the qty detected was, to int32
{
int previousStringNum = Int32.TryParse(previousLine.Substring(previousLine.LastIndexOf(" ") + 1)
int sumOfLineAndPreviousLine = lineInt + previousStringNum;
//set the line variable equal to its new value which includes the value from the previous line
line = line.substring(0, line.length - 2) + sumOfLineAndPreviousLine.ToString();
//textBox2.Text += line + lineInt+Environment.NewLine.ToString();
//set the previousLine variable equal to line so that the next pass of the foreach loop if that object equals the object in previousLine, it will continue to add them...
previousLine = line;
}
}
catch (Exception)
{
}
}
else
{
//the object in this line is not equal to the object in the previousLine
//so append the previousLine to the TextBox2.Text and then
//set the previousLine object equal to the current Line so that on the
//next pass of the loop will work correctly
textBox2.Text = textBox2.Text + previousLine;
previousLine = line;
}
}
}
I believe this may achieve what you want, although it is rather limited. This assumes all of the objects will only have one digit. The code will need to be altered to handle double digit numbers etc.

Calculation in DataGridView column

I have a DataGridView in which I want to sum up values from two different columns into a third column.
Example DataGridView:
A B Total
1 2 3
25 35 60
5 -5 0
I want to add (A+B) in total, just after entering values in A & B column or leaving current row. And also want to set Total Column as ReadOnly.
You can do that on CellValidatedEvent and you can apply the same method to RowValidated:
private void dataGridView_CellValidated(object sender, DataGridViewCellEventArgs e) {
if (e.RowIndex > -1) {
DataGridViewRow row = dataGridView.Rows[e.RowIndex];
string valueA = row.Cells[columnA.Index].Value.ToString();
string valueB = row.Cells[columnB.Index].Value.ToString();
int result;
if (Int32.TryParse(valueA, out result)
&& Int32.TryParse(valueB, out result)) {
row.Cells[columnTotal.Index].Value = valueA + valueB;
}
}
}
You can set column to ReadOnly in the designer, or like this:
dataGridView.Columns["Total"].ReadOnly = true
You could easily do this
But you should have a dataset or localdatabase connection like SQL
I will assume that you got it and name it
Totaldataset.
Easily done I know it's too late answer but maybe it help some new readers.
Datacolumn column = new Datacolumn ();
column.Columnname = "Total";
Totaldataset.Tables[0].Columns.["Total"].Expression = "a+b";
This is a working example:
public partial class Form1 : Form
{
DataGridView _calcDataGridView;
public Form1()
{
InitializeComponent();
_calcDataGridView = new DataGridView();
this.Controls.Add(_calcDataGridView);
_calcDataGridView.Dock = DockStyle.Fill;
_calcDataGridView.Name = "CalcDataGridView";
_calcDataGridView.CellEndEdit += Calculate;
var aColumn = new DataGridViewTextBoxColumn();
aColumn.Name = "AColumn";
aColumn.HeaderText = "A";
_calcDataGridView.Columns.Add(aColumn);
var bColumn = new DataGridViewTextBoxColumn();
bColumn.Name = "BColumn";
bColumn.HeaderText = "B";
_calcDataGridView.Columns.Add(bColumn);
var totalColumn = new DataGridViewTextBoxColumn();
totalColumn.Name = "TotalColumn";
totalColumn.HeaderText = "Total";
totalColumn.ReadOnly = true;
_calcDataGridView.Columns.Add(totalColumn);
}
private void Calculate(object sender, DataGridViewCellEventArgs e)
{
object a = _calcDataGridView.CurrentRow.Cells["AColumn"].Value;
object b = _calcDataGridView.CurrentRow.Cells["BColumn"].Value;
double aNumber = 0;
double bNumber = 0;
if (a != null)
aNumber = Double.Parse(a.ToString());
if (b != null)
bNumber = Double.Parse(b.ToString());
_calcDataGridView.CurrentRow.Cells["TotalColumn"].Value = aNumber + bNumber;
}
}
If U r using data binding using Eval
than U can just create a method there and on that method just sum those two values.
Like
For Column A
<ItemTemplate>
<%# Eval("A")%>
</ItemTemplate>
for column B
<ItemTemplate>
<%# Eval("B")%>
</ItemTemplate>
For Total
<ItemTemplate>
<%# GetTotal(Eval("A"),Eval("B")) %>
</ItemTemplate>
For total method
private string GetTotal(object A,object B)
{
return (A+B).ToString();
}
hope this will help you.

Categories

Resources