foreach loop within mvc model - c#

I'm stuck on a problem trying to get a foreach block of code to work within an mvc controller and viewmodel.
What i'm trying to achieve is loop through the datetime values and if less than 60 seconds, show seconds. if more than 60 seconds but less than 1 hour show minutes. else show full datetime.
I can get the above to work, but it only displays the 1st record. I have tried putting foreach loops in various places but just cannot seem to get it to work.
Would appreciated a fresh pair off eyes to help with this.
public class MostRecentPostsViewModel
{
public List<MembersForumProperties> SelectMostRecentForumPosts { get; set; }
public string DateAndTimeOfForumPosts { get; set; }
}
public class IsPostLessThanOneHour
{
public static string DisplayPostInMinutesOrSeconds(string displyMostRecentForumPosts)
{
string displayTime = string.Empty;
//foreach (var postTime in mv.SelectMostRecentForumPosts)
//{
// dte = postTime.ForumMemberDateTimePostedPost;
//}
DateTime dtn = DateTime.Now;
DateTime timeOfPost = Convert.ToDateTime(displyMostRecentForumPosts);
TimeSpan ts = dtn - timeOfPost;
if (ts.TotalSeconds > 0 && ts.TotalSeconds < 60)
{
displayTime = "about " + ts.Seconds + " seconds ago";
}
else if (ts.TotalSeconds > 61 && ts.TotalSeconds < 3600)
{
displayTime = "about " + ts.Minutes + " minutes ago";
}
else
{
displayTime = displyMostRecentForumPosts;
}
return displayTime;
}
}
Controller
public PartialViewResult MostRecentMembersPosts()
{
var displyMostRecentForumPosts = _imf.DisplayMostRecentForumPosts().ToList();
var loopThroughDateTimes = displyMostRecentForumPosts.ToList();
var test = "";
foreach (MembersForumProperties t in loopThroughDateTimes)
{
test = t.ForumMemberDateTimePostedPost;
}
var membersMostRecentPost = new MostRecentPostsViewModel
{
SelectMostRecentForumPosts = displyMostRecentForumPosts,
DateAndTimeOfForumPosts = IsPostLessThanOneHour.DisplayPostInMinutesOrSeconds(test)
};
return PartialView("pvMostRecentMembersPost",membersMostRecentPost);
}

Why not just send the dates down as is and use a JS plugin like TimeAgo e.g.
public PartialViewResult MostRecentMembersPosts()
{
return PartialView("pvMostRecentMembersPost", _imf.DisplayMostRecentForumPosts().ToList());
}
Then in your view
#model IEnumerable<MemberForumProperties>
<!-- Head section would need to be defined in your master page first -->
#section Head {
<script src="jquery.timeago.js" type="text/javascript"></script>
<script type="text/javascript">
$.ready(function() {
$("abbr.timeago").timeago();
});
</script>
}
#foreach (var m in Model)
{
<abbr class="timeago" title='#m.ForumMemberDateTimePostedPost.ToString("s")' />
}
TimeAgo will take care of converting your DateTime values into a fuzzy timestamp.
The Problem
If you don't want to go for the client-side approach, then to fix your current server-side issue you need to send down a list of relative times, at the minute you only appear to be sending down the last relative time i.e.
var test = "";
foreach (MembersForumProperties t in loopThroughDateTimes)
{
test = t.ForumMemberDateTimePostedPost;
}
// test now contains the date/time of the last item in the `loopThroughDateTimes` list
var membersMostRecentPost = new MostRecentPostsViewModel
{
SelectMostRecentForumPosts = displyMostRecentForumPosts,
DateAndTimeOfForumPosts = IsPostLessThanOneHour.DisplayPostInMinutesOrSeconds(test)
};
// DateAndTimeOfForumPosts only contains the relative string for the last date/time
Your current setup just appears a bit messy & cluttered and not very readable.
The Solution
To tidy it up a bit here's what I would do
public static class DateTimeExt
{
public static string ToRelativeTime(this DateTime value)
{
// you could move the entire implementation of `DisplayPostInMinutesOrSeconds` to here
return IsPostLessThanOneHour.DisplayPostInMinutesOrSeconds(value);
}
}
...
public PartialViewResult MostRecentMembersPosts()
{
return PartialView("pvMostRecentMembersPost", _imf.DisplayMostRecentForumPosts().ToList());
}
And then in your view
#model IEnumerable<MemberForumProperties>
#foreach (var props in Model)
{
<p>#props.ForumMemberDateTimePostedPost.ToRelativeTime()</p>
}

Related

Print elements from a list in ascending order(date) whilst splitting the line by each day- C#

I am trying to print the following in ascending order of the date :
static void Main(string[] args)
{
string meter_id = "08002220";
string calc_constant = "0.1";
string interval = "00000100";
List<DateTime> readingDate = new List<DateTime>();
List<float> volume = new List<float>();
List<float> odometer = new List<float>();
var get_timestamp = DateTime.Now.ToString("yyyyMMddHHmm");
try
{
TextReader textReader = File.OpenText(#"C:\Users\umar\Documents\data format\test.csv");
var csv = new CsvReader(textReader);
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
readingDate.Add(DateTime.Parse(csv["Reading Date"]));
volume.Add(float.Parse(csv["Total Volume"]) / 1000);
odometer.Add(float.Parse(csv["Odometer"]) / 1000);
}
readingDate.Sort();
var printCMREG = readingDate.Zip(odometer, (first, second) => new { first, second });
var printCM = readingDate.Zip(volume, (first, second) => new { first, second });
Console.Write($" MEPMD01, 20080501, EDDYIQ, INSWT:053000,,,{get_timestamp},,OK,W,CMREG,{calc_constant},{interval},");
foreach (var print in printCMREG)
{
if (print.first.Hour == 0)
{
Console.Write($"{print.first.ToString("yyyyMMddHHmm")},R0,{print.second},");
}
}
Console.WriteLine("\n");
Console.Write($" MEPMD01, 20080501, EDDYIQ, INSWT:053000,,,{get_timestamp},,OK,W,CM,{calc_constant},{interval},");
foreach (var print in printCM)
{
Console.Write($"{print.first.ToString("yyyyMMddHHmm")},R0,{print.second},");
}
}
catch(System.IO.IOException e)
{
Console.WriteLine(e);
}
}
I have written the above code, which prints the date and time equivalent of a meter reading. What I need at the moment is the ability to sort the dates at the bottom in 24 hour format.
Console.Write($" MEPMD01, 20080501, EDDYIQ, INSWT:053000,,,{get_timestamp},,OK,W,CM,{calc_constant},{interval},");
foreach (var print in printCM)
{
Console.Write($"{print.first.ToString("yyyyMMddHHmm")},R0,{print.second},");
}
As can be seen in this line, this prints all the dates together, however, I want to split it up in 24 intervals.
Replace this loop:
foreach (var print in printCM)
{
Console.Write($"print.first.ToString("yyyyMMddHHmm")},R0,print.second},");
}
With this:
DateTime currentDay = null;
foreach (var print in printCM)
{
if(currentDay == null)
{
currentDay = print.first.Date;
}
else if(currentDay != print.first.Date)
{
Console.WriteLine();
currentDay = print.first.Date;
}
Console.Write($"{print.first.ToString("yyyyMMddHHmm")},R0,{print.second},");
}
It will see if the prints are on the same date. If not it will insert a newline and then update the currentDay variable.
This assumes your sort used earlier in your code is in fact sorting the list.
It would be better if you created a class and updated the variables in there, something like this, than you could just run a foreach each loop on the print them out.
public class CSVData
{
public DateTime ReadingDate { get; set; }
public float Volume { get; set; }
public float Odometer { get; set; }
}

maximum and minimum value in list

I'm currently doing my current project and I had a problem. Here's what the project needs to do:
Find the maximum and the minimum temperature from a certain range of date. The range of the date will be inputted by the user.
So, I make a form as the main menu for inputting the items and finding the maximum and minimum value (both in the new form). I also make a class to store the items:
public class TempDate
{
public double Temp { get; set; }
public DateTime Date { get; set; }
}
In the first form, just call it FormAddData, from here items will be stored into the list using a textbox and here's the code:
private void buttonSubmit_Click(object sender, EventArgs e)
{
FormMenu formMenu = (FormMenu)this.Owner;
DateTime date = dateTimePickerDate.Value.Date;
double temp = double.Parse(textBoxTemp.Text);
TempDate tempDate = new TempDate();
tempDate.Date = date;
tempDate.Temp = temp;
formMenu.listOfTempDate.Add(tempDate);
listBoxInfo.Items.Add(date + "\t" + temp + "°C");
}
In the second form that called FormMaxMinRange. In this form, I use two DateTimePicker the first one for the starting date and the second for the ending date. From here I need to make a button that will select all the items from the range that I used from starting and ending date. Here's my code:
private void buttonMaxMin_Click(object sender, EventArgs e)
{
FormMenu formMenu = (FormMenu)this.Owner;
DateTime start = dateTimePickerStart.Value.Date;
DateTime end = dateTimePickerEnd.Value.Date;
int highest = 0;
double max = formMenu.listOfTempDate[0].Temp;
int lowest = 0;
double min = formMenu.listOfTempDate[0].Temp;
for (int i = 1; i < formMenu.listOfTempDate.Count; i++)
{
if (formMenu.listOfTempDate[i].Date >= start
&& formMenu.listOfTempDate[i].Date <= end)
{
if (formMenu.listOfTempDate[i].Temp > max)
{
highest = i;
max = formMenu.listOfTempDate[i].Temp;
}
if (formMenu.listOfTempDate[i].Temp < min)
{
lowest = i;
min = formMenu.listOfTempDate[i].Temp;
}
}
}
listBoxMaxMin.Items.Add("");
listBoxMaxMin.Items.Add("Lowest temp: " + min + ", on " + formMenu.listOfTempDate[lowest].Date);
listBoxMaxMin.Items.Add("Highest temp: " + max + ", on " + formMenu.listOfTempDate[highest].Date);
}
Here's the main form that i declared the class (which include the list):
public partial class FormMenu : Form
{
public List<TempDate> listOfTempDate = new List<TempDate>();
public FormMenu()
{
InitializeComponent();
}
private void fromCertainRangeToolStripMenuItem_Click(object sender, EventArgs e)
{
FormMaxMinRange formMaxMinRange = new FormMaxMinRange();
formMaxMinRange.Owner = this;
formMaxMinRange.ShowDialog();
}
}
But, the problem is, the minimum value was not selected inside the range of selection. Also I want the max and min value was printed in the listbox. Sorry for the long and weird question. I hope someone can understand what I means with this question to complete my project. Thank you.
See this code snippet.
You can use Linq to select the reduced list (with Start/Enddate) and order it by Temp. Now you can easy select the first (min) and the last (max) object.
List<TempDate> loTempDateList = new List<TempDate>()
{
new TempDate() {Date = DateTime.Now.AddDays(-10), Temp = 10.01 },
new TempDate() {Date = DateTime.Now.AddDays(-5), Temp = 20.01 },
new TempDate() {Date = DateTime.Now.AddDays(-3), Temp = 30.01 },
new TempDate() {Date = DateTime.Now, Temp = 40.01 }
};
DateTime ldStart = DateTime.Now.AddDays(-6);
DateTime ldEnd = DateTime.Now.AddDays(-1);
var loDateList = loTempDateList.Where(item => item.Date <= ldEnd && item.Date >= ldStart)
.OrderBy(item => item.Temp);
TempDate loMin = loDateList.First();
TempDate loMax = loDateList.Last();
Console.WriteLine("{0}: {1} with max temp", loMax.Date, loMax.Temp);
Console.WriteLine("{0}: {1} with min temp", loMin.Date, loMin.Temp);
Output (for today):
9/26/2017 3:17:09 PM: 30.01 with max temp
9/24/2017 3:17:09 PM: 20.01 with min temp
Update (with your variable names):
Copy this under DateTime end = dateTimePickerEnd.Value.Date;in your Form
var loDateList = listOfTempDate.Where(item => item.Date <= end && item.Date >= start)
.OrderBy(item => item.Temp);
TempDate loMin = loDateList.FirstOrDefault();
TempDate loMax = loDateList.LastOrDefault();
if (loMin != null && loMax != null)
{
listBoxMaxMin.Items.Add("");
listBoxMaxMin.Items.Add("Lowest temp: " + loMin.Temp + ", on " + loMin.Date);
listBoxMaxMin.Items.Add("Highest temp: " + loMax.Temp + ", on " + loMax.Date);
}
I would suggest you use Linq Max and Min methods.
// filter out only the dates in the range you need
var items = formMenu.listOfTempDateWhere(
item => ((TempDate)item).Date >= start && ((TempDate)item).Date <= end
);
// get the maximum value
var max = items.Max(item => item.Temp);
// get the minimum value
var min = items.Min(item => item.Temp);
Just remember to add using System.Linq on the top of your .cs file
try this online
If you don't like a LINQ approach (I never use LINQ, for some, possibly invalid reason, I think it's evil), you can override the List class and extend it with methods of your own.
public class TempDataList<T> : List<TempData>
{
public TempDataList() : base()
{
}
public TempDataList(IEnumerable<TempData> collection) : base(collection)
{
}
public TempData GetMaxTemp(DateTime startDate, DateTime endDate)
{
TempData highestTempData = null;
for (int i = 0; i < this.Count; i++)
{
if (this[i].Date >= startDate && this[i].Date <= endDate)
{
if (highestTempData == null || this[i].Temp > highestTempData.Temp)
{
highestTempData = this[i];
}
}
}
return highestTempData;
}
public TempData GetMinTemp(DateTime startDate, DateTime endDate)
{
TempData lowestTempData = null;
for (int i = 0; i < this.Count; i++)
{
if (this[i].Date >= startDate && this[i].Date <= endDate)
{
if (lowestTempData == null || this[i].Temp < lowestTempData.Temp)
{
lowestTempData = this[i];
}
}
}
return lowestTempData;
}
}
And fill the extended list and call the methods:
TempDataList<TempData> tempDataList = new TempDataList<TempData>();
tempDataList.Add(new TempData(10, DateTime.UtcNow));
tempDataList.Add(new TempData(20, DateTime.UtcNow));
tempDataList.Add(new TempData(15, DateTime.MinValue));
tempDataList.Add(new TempData(25, DateTime.MaxValue));
Console.WriteLine(tempDataList.GetMaxTemp(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1)).Temp);
Console.WriteLine(tempDataList.GetMinTemp(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1)).Temp);

Increase value of session variable for each call to controller

Each time a click on a link in the View and call an ActionResult method in the Controller, I need to increase the value of the session variable, but it's not working.
When I start the value is 17 and when I click on the link and pass 1 to the Controller I want the result to be 18 and next time I click it should be 19.
But what have I done wrong and how can I improve the code? The value is a nullable int in the ActionResult.
public ActionResult Index(int? value) {
// Session
if (Session["week"] == null)
{
// Create session
Session["week"] = week.WeekNum();
}
if (!value.HasValue)
{
weekStart = (int)Session["week"];
}
else
{
Session["week"] = + value;
weekStart = (int)Session["week"];
}
ViewBag.weekNumber = weekStart;
... the rest of the code...
}
I suggest writing a helper function to do the increment e.g.
private void IncrementWeeks(int weeks)
{
if (Session["week"] == null)
{
Session["week"] = week.WeekNum();
return;
}
int currentWeek = 0;
if (int.TryParse(Session["week"].ToString(), out currentWeek))
{
Session["week"] = (currentWeek + weeks).ToString();
}
}
Just to cover NULL checking and int conversion issues.
Here's how you could wrap getting the value from the session into a helper function too:
private int ReadWeekFromSession()
{
if (Session["week"] == null)
{
return 0;
}
int currentWeek = 0;
if (int.TryParse(Session["week"].ToString(), out currentWeek))
{
}
return currentWeek;
}
For example:
public ActionResult Index(int? value)
{
int weekStart = 0;
if (!value.HasValue)
{
weekStart = ReadWeekFromSession();
}
else
{
IncrementWeeks(value.Value);
weekStart = ReadWeekFromSession();
}
// Rest of controller code....
}
You'd increment the value just like you would from any other data source:
Retrieve the value
Modify the value
Store the new value
Which could be something as simple as:
var weekValue = int.Parse(Session["week"].ToString());
weekValue += value;
Session["week"] = weekValue;
If it's possible that the session variable isn't a valid integer, you might use int.TryParse() instead or some other means of checking for that condition.
Or to avoid using that .ToString() call, if the potential for errors with the value is small enough to use int.Parse() in the first place then I suppose you could get away with this as well:
var weekValue = Convert.ToInt32(Session["week"]);
Which is a bit more forgiving on the input types, since it has many overloads.

How to use Razor efficiently

I'm trying to implement this algorith in a View page using Razor, but, it does not display the expected result and I don't get any compilation errors. Any suggestion please ?
Edit : I apologize I was not very clear, I confess. My problem is that I do not understand why ViewBag.NbrePages is equal to 0. However, the database had been filled.
Action();
[HttpGet]
public ActionResult Rechercher(string rech, string type, int num = 1)
{
int nbLignesDepassees = 10 * (num - 1);
ViewBag.Recherche = Server.HtmlEncode(rech);
ViewBag.Type = Server.HtmlEncode(type);
ViewBag.NumPgeCourrante = num;
if (type == "nomAppMetier")
{
var appsMetiers = _db.AppsMetiers
.Where(x => SqlFunctions.PatIndex("%" + rech + "%", x.nomApplication) > 0)
.OrderBy(x => x.nomApplication)
.Skip(nbLignesDepassees)
.Take(10);
ViewBag.NbrePages = (int)(appsMetiers.Count() / 10) ;
return View("RechercheAppsMetiers",appsMetiers);
}
if (type == "nomPoste")
{
var postes = _db.Postes
.Where(x => SqlFunctions.PatIndex("%" + rech + "%", x.nomPoste) > 0)
.OrderBy(x => x.nomPoste)
.Skip(nbLignesDepassees)
.Take(10);
ViewBag.NbrePages = (int)(postes.Count() / 10);
return View("RecherchePostes", postes);
}
return HttpNotFound();
}
View();
<ul>
#{
for (int i = 0; i < ViewBag.NbrePages; i++)
{
if(i==1 || i==2 || i==3){
<li class="disabled">&maquo;</li>
}else{
<li>«</li>
}
if (i == ViewBag.NumPgeCourrante)
{
<li class="active">#i <span class="sr-only">(current)</span></li>
}
else
{
<li>#i </li>
}
if(i==ViewBag.NbrePages || i==ViewBag.NbrePages-1 || i==ViewBag.NbrePages-2){
<li class="disabled">»</li>
}else{
<li>»</li>
}
}
}
</ul>
Thanks a lot !
Rather than having so much logic in the view, consider the following:
A model
public class PagesModel
{
public int NumberOfPages { get; set; }
public int CurrentPage { get; set; }
}
A helper method in a class
public static class Helpers
{
public static bool GetClassNames(int page, int totalPages, int currentPage)
{
var classNames = new List<string>();
var isWithinFirstOrLastThree = page <= 2 || page >= (totalPages - 2);
if (isWithinFirstOrLastThree)
{
classNames.Add("disabled");
}
if (page == currentPage)
{
classNames.Add("active");
}
return string.Join(" ", classNames.ToArray());
}
}
And then your view could be as simple as
#model PagesModel
#for (int i = 0; i < Model.NumberOfPages; i++)
{
<li class="#Helpers.GetClassNames(i, Model.NumberOfPages, Model.CurrentPage)">
&maquo;
#i
</li>
}
This doesn't exactly match what you are trying to achieve, but I hope that it is helpful nonetheless.
NbrePages will be either 0 or 1 (if you have more that 10 records) due to Take(10) and using integer division:
ViewBag.NbrePages = (int)(appsMetiers.Count() / 10) ;
So most likely you get less that 10 items in appsMetiers.
Suggestion to improve source based on original misspelling of the variable in CSHTM:
Using good names or strongly typed model would help to avoid spelling like NbrePges in for condition in original post:
for (int i = 0; i < ViewBag.NbrePages; i++)
CSHTML files are not compiled till run-time access, so no compile errors. Since ViewBag allows any property to be used you are not getting any intellisense warning either.
Instead of ViewBag consider some strongly typed model or at least put strongly typed object for paging into ViewBag:
class PagingState
{
public int NumberOfPages { get;set;}
public int CurrentPage { get;set;}
}
and in view:
var pageingState = (PagingState)(ViewBag.Paging);
for(int I = 0; i < pageingState.NumberOfPages; i++)...

Unexpected behaviour of dynamic html rendering a table with data via C#

I'm encountering an unfamiliar problem with functionality. I think it has something to do with scope of a loop, and server-side code operations/manipulation when rendering a page.
Say I want to repeat a Table Row - each hosts a text input, rows and their textboxes are rendered with values according to content of DATABASE "binded" Data.
Everything works perfectly until more requirements are added - READONLY Attribute And event Key (javascript small validation task).
Otherwise it does work, alternating rows via two separated strings that I "inject" with string format on a condition of if row count is odd vs even, then I tried to filter some of columns to have a keypress event bound to a js function and another attribute as a string.
If the string is empty, then end part of the element "declaration" will be empty
if condition was met, then that string is assigned with value "ReadOnly" and js string is assigned with keypress event "calling a function code".
Here's the code. The situation is weird as style attributes, information of current column, columns names, everything does function as expected but those two READONLY Attribute And event Key (javascript small validation task) that do not.
Render a dynamic Table Code
This is the front code, c# code behind is used mostly (to keep a little code client-side as possible)
`ControlsInteraction.WithTable.Design()`
AND
`ControlsInteraction.WithTable.ExtractData()`
are dealing with dynamic functions of rendering and translation of columns names and values
int count = 0;
bool TblOk = DebugTests.Sesseion.SeSn.Raised(DebugTests.Flag.HT_DB_CPA_Table_init_Complete);
if (TblOk)
{
string TextBxRendr = "";//holds Renderd <TD> base String-code
string AltrnatBgColor;
string NoAttribute = "";
string Js_NumericKprss = "onkeypress=\"return onlN(event)\""
string ReadOnly = "READONLY";
var TimesCol = ALLTablesDataSet.Tables[Tbl1.TableName].Columns;
string DtrawTbl1 = Tbl1.TableName;
ControlsInteraction.WithTable.Design Tbldz =
new ControlsInteraction.WithTable.Design();
ControlsInteraction.WithTable.ExtractData DtExtrct =
new ControlsInteraction.WithTable.ExtractData();
foreach (System.Data.DataRow TimesRow in ALLTablesSet.Tables[DtrawTbl].Rows)
{
AltrnatBgColor= Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"),true);
altBgColOnly = Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"), false);
Response.Write(string.Format("<tr {0}>",AltrnatBgColor));
for (int i = 0; i < TimesRow.ItemArray.Length; i++)
{
if (i != (TimesRow.ItemArray.Length - 1))
{
Js_NumericKprss = "onkeypress=\"return onlN(event)\"";
//asking for: current row will Not be read only via its name
if (DtExtrct.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.Comments, DtExtrct.DataRowToInt(TimesRow, "RecordNum")))
Js_NumericKprss = NoAttribute; // same goes with the other manipulation i've needed to implement on each column
TextBxRendr = string.Format(
"<td><input type='text' id=\"{0}_{1}\" value=\"{2} \" style=\"width:50px;{3} border:none; \" class=\"RepTblDataTDs\" {4} {5} \\></td>",
TimesCol[i], TimesRow["RecordNum"], TimesRow[i], AltrnatBgColor,Js_NumericKprss,ReadOnly
);
}
else
{
TextBxRendr = string.Format(
"<td><input type='image' id=\"{0}_{1}\" src=\"images/Save.png\" style=\"width:25px;{2}\" style=\"width:25px\" onclick=\"UbpdateTblCPA(this, {1});\" /></td>",
"img",i + 1, AltrnatBgColor
);
}
Response.Write(TextBxRendr);
count++;
}
}
}
Is injected properly and the read only part READONLY Attribute, and event Key - (javascript small validation task)
Either functions on all or none
What am I doing wrong?
answering my own Question aventually answer is
...well everything , including #Patrics Comment Was Wrong
i can just say put good attention to : how to work with DataTable DataRow, DataTable DataColumns
and the relations for and foreach variables scope
use your visual sudio debugger on every line to check on your codes values
i did not have the time to rename variables but if you need to make a dynamic
html table out of a DB table this is the way
foreach (System.Data.DataRow TimesRow in ALLTablesSet.Tables[DrawTbl].Rows)
{
recordNum = RDE.DataRowToInt(TimesRow, "RecordNum");
AltBgCol = Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"), true);
altBgColOnly = Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"), false);
Response.Write(string.Format("<tr {0}>", AltBgCol));
for (int i = 0; i < TimesRow.ItemArray.Length; i++)
{
if (i != (TimesRow.ItemArray.Length - 1))
{
Js_NumericKprss = "onkeypress=\"return onlN(event)\""; ReadOnly = "";
if (RDE.CurrRowIs(TimesRow, HentalDBSchema.HTDB_Cols.TblTimeCPAReport.Comments, i))
{
Js_NumericKprss = ""; ReadOnly = "";
}
else if (RDE.CurrRowIs(TimesRow, HentalDBSchema.HTDB_Cols.TblTimeCPAReport.Fines, i)
|| RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.PhoneExpences, i)
|| RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.SalaryPerDay, i)
|| RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.SalaryPerMonth, i)
|| RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.TotalGrossWages, i)
|| RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.TravelFee, i))
{
ReadOnly = "";
Js_NumericKprss = "onkeypress=\"return onlN(event)\"";
}
else
ReadOnly = "READONLY";
TxtRndr = string.Format("<td><input type='text' id=\"{0}_{1}\" value=\"{2} \" style=\"width:50px;{3} border:none; \" class=\"RepTblDataTDs\" {5} {6} \\></td>{4}", TimesCol[i], TimesRow["RecordNum"], TimesRow[i], altBgColOnly, Environment.NewLine + "\t\t\t", Js_NumericKprss, ReadOnly);
}
else
{
TxtRndr = string.Format("<td><input type='image' id=\"{0}_{1}\" src=\"images/Save.png\" style=\"width:25px;{3}\" style=\"width:25px\" onclick=\"UbpdateTblCPA(this, {1});\" /></td>{4}", "imgBut", i + 1, TimesRow[i], altBgColOnly, Environment.NewLine + "\t\t\t");
}
Response.Write(TxtRndr);
count++;
}
}
i am adding all researches i have made to be more easy on the data extraction and some more methods i have worked on so if u like to use it feel free to ...
public class ControlsInteraction
{
public class WithDDL
{
public class GetSelVal
{
public string AsString(DropDownList DDLToCollectValusFrom)
{
return DDLToCollectValusFrom.SelectedValue;
}
public int AsInt(DropDownList DDLToCollectValusFrom)
{
if(DDLToCollectValusFrom.SelectedValue != null)
return Convert.ToInt32(DDLToCollectValusFrom.SelectedValue);
return 666;
}
}
public List<string> GetListItems_Values(DropDownList DDLToCollectValusFrom)
{
List<string> LST_DDLValues = new List<string>();
foreach (ListItem item in DDLToCollectValusFrom.Items)
{
LST_DDLValues.Add(item.Value);
}
return LST_DDLValues;
}
public List<string> GetListItems_Text(DropDownList DDLToCollectTextFrom)
{
List<string> LST_DDLTEXT = new List<string>();
foreach (ListItem item in DDLToCollectTextFrom.Items)
{
LST_DDLTEXT.Add(item.Text);
}
return LST_DDLTEXT;
}
}
public static class WithPlcHldr
{
public static void AddCtrl(PlaceHolder PlcHldrID, Control CntrID)
{
PlcHldrID.Controls.Add(CntrID);
}
}
public class WithTable
{
public class Design
{
public string RowsBGColorAlternate(int RowCounter, bool AddWithStyleAsStandAlone = false)
{
string BgCol = ""; bool bgclaltrnator;
if (RowCounter > 0)
{
RowCounter++;
bgclaltrnator = (RowCounter % 2) == 0;
if (bgclaltrnator)
BgCol = "#70878F";
else BgCol = "#E6E6B8";
}
if (AddWithStyleAsStandAlone)
return string.Format("style=\"background-color:{0};\"", BgCol);
return string.Format("background-color:{0};", BgCol);
}
}
public class ExtractData
{
public string ColumnValueFromCurrRow(DataRow DtRow, string RequestedColName)
{
return "";
}
public string DataRows_ColumnToString(DataRow Data_RowToActOn, string keyColName)
{
var tmp = Data_RowToActOn[keyColName];
return Data_RowToActOn[keyColName].ToString();
}
public int DataRowToInt(DataRow Data_RowToActOn, string keyColName)
{
string tmp = Data_RowToActOn[keyColName].ToString();
return Convert.ToInt32(tmp);
}
public bool CurrColumnIs(DataColumn Data_RowToQuestion, string ColumnName)
{
string tmp = Data_RowToQuestion.ToString();
return tmp == ColumnName;
}
public bool CurrRowIs(DataRow Data_RowToQuestion, string RowName, int CurrIndex)
{
string ColsName = Data_RowToQuestion.Table.Columns[CurrIndex].ToString();
return ColsName == RowName;
//this is curent value - by index
//string currentColumn = Data_RowToQuestion.ItemArray[CurrIndex].ToString();
}
}
}
}

Categories

Resources