Extracting values of textbox in array? - asp.net

I have dynamically created textbox in asp.net. Now i am extracting the values through following code.
string[] sublist = new string[] { };
int[] maxmarkslist = new int[] { };
int i;
for (i = 0; i < Convert.ToInt32(Label15.Text); i++)
{
string sub = "subject" + i;
string marks = "maxmarks" + i;
TextBox subject = (TextBox)PlaceHolder1.FindControl(sub);
TextBox maxmarks = (TextBox)PlaceHolder1.FindControl(marks);
sublist[i] = subject.Text;
maxmarkslist[i] = Convert.ToInt32(maxmarks.Text);
}
But I getting error "Index was outside the bounds of the array" for the below two lines:
sublist[i] = subject.Text;
maxmarkslist[i] = Convert.ToInt32(maxmarks.Text);
When I debugged it, values are coming in subject.Text and maxmarks.Text but not going to array.
Did I define the array in a wrong way?

You define both the arrays as empty arrays. So you will get index out of bound erros if you try to index into those.
Arrays are not dynamically expanding. If you want that, use a collection type and may be later convert to an array.
Try this:
int length = Convert.ToInt32(Label15.Text);
string[] sublist = new string[length-1];
int[] maxmarkslist = new int[length-1];
for (int i = 0; i < length; i++)
{
string sub = "subject" + i;
string marks = "maxmarks" + i;
TextBox subject = (TextBox)PlaceHolder1.FindControl(sub);
TextBox maxmarks = (TextBox)PlaceHolder1.FindControl(marks);
sublist[i] = subject.Text;
maxmarkslist[i] = Convert.ToInt32(maxmarks.Text);
}
Or here is how to do this with a collection (List) type:
int length = Convert.ToInt32(Label15.Text);
List<string> sublist1 = new List<string>();
List<int> maxmarkslist1 = new List<int>();
for (int i = 0; i < Convert.ToInt32(Label15.Text); i++)
{
string sub = "subject" + i;
string marks = "maxmarks" + i;
TextBox subject = (TextBox)PlaceHolder1.FindControl(sub);
TextBox maxmarks = (TextBox)PlaceHolder1.FindControl(marks);
sublist1.Add(subject.Text);
maxmarkslist1.Add(Convert.ToInt32(maxmarks.Text));
}
string[] sublist = sublist1.ToArray();
int[] maxmarkslist = maxmarkslist1.ToArray();
Note with collections you dont have to specify the size upfront. But keep adding items to it as it can expand as needed. But arrays can not do this.
Your string[] sublist = new string[] { }; is a shortcut method where you create and initialize the array. In that you don't have to specify the size, but compiler will count the elements between {} and set the size appropriately. In your case since there are no elements inside {} it will create an empty array.

string[] sublist = new string[100];
int[] maxmarkslist = new int[100];
Put this..replace 100 with the max possible value of your loop...but this is not a good practice...will come back to this thread if i found something better...

Related

How to get User ID or GUID from BMC Remedy User using Java

I am using the Remedy API for Java.
How do I get a User ID or the User GUID from a Remedy User using java?
I do a simple logon using something like the following:
ARServerUser sUser = new ARServerUser("server", "port", "user", "pass", 1);
The sUser object however does not have any userid or guid inside it?
I have looked at the API and cannot find a method to retrieve it. I have also tried looking in the UserInfo object, but that also doe not contain it?
Any ideas?
Thanks
Sample code to fetch ALL details for a User.
ARServerUser arConnection = new ARServerUser("server", "port", "user", "pass", 1);
List<SortInfo> sortList = new ArrayList<SortInfo>();
int firstRetreive = 0;
int maxRetreive = maxNumEntries;//1M
OutputInteger numMatches = new OutputInteger();
ResultEntryList iterator = new ResultEntryList(data);
QualifierInfo qiPlain = new QualifierInfo();
//make field list for results
List<Field> fields = arConnection.getListFieldObjects(formName);
ArrayList<Integer> alFieldIds = new ArrayList<Integer>();
for (int x = 0; x <
fields.size(); x++) {
alFieldIds.add(fields.get(x).getFieldID());
}
int[] fieldIds = new int[alFieldIds.size()];
for (int i = 0; i < fieldIds.length; i++) {
fieldIds[i] = ((Integer) alFieldIds.get(i)).intValue();
}
arConnection.getListEntryObjects("User", qiPlain, firstRetreive, maxRetreive, sortList, fieldIds, false, numMatches, iterator);
If you just want the ids, you can skip the retrieval of all the field IDs. unfortunately I cannot remember the ID of the username field. Substitute the xxx with its ID)
ARServerUser arConnection = new ARServerUser("server", "port", "user", "pass", 1);
List<SortInfo> sortList = new ArrayList<SortInfo>();
int firstRetreive = 0;
int maxRetreive = maxNumEntries;//1M
OutputInteger numMatches = new OutputInteger();
ResultEntryList iterator = new ResultEntryList(data);
QualifierInfo qiPlain = new QualifierInfo();
//make field list for results
int[] fieldIds = {Constants.AR_CORE_ENTRY_ID, xxx};
arConnection.getListEntryObjects("User", qiPlain, firstRetreive, maxRetreive, sortList, fieldIds, false, numMatches, iterator);

Linechart show info on point tapped

I'm implementing a little app with Xamarin Forms for a web page, the thing is that in this web is a linear chart with multiple entries and if the user clicks on a point of the line shows info about that point, as you can see in the picture:
Web Line Chart
After some work, I could create a more or less similar line chart using the OxyPlot.Xamarin.Forms plugin with multiple entries which shows the points
My App Line Chart
This is my code:
OnPropertyChanged("GraphModel");
var model = new PlotModel
{
LegendPlacement = LegendPlacement.Outside,
LegendPosition = LegendPosition.BottomCenter,
LegendOrientation = LegendOrientation.Horizontal,
LegendBorderThickness = 0
};
model.PlotType = PlotType.XY;
model.InvalidatePlot(false);
Dictionary<string, List<Prices>> values = HistoricData[Selected.ProductId];
int colorIndex = 0;
List<string> x_names = new List<string>();
foreach (var item in values.Keys)
{
if (item.ToUpper() == Selected.ProductName) { SelectedIndex = colorIndex; }
var lineSeries = new LineSeries()
{
Title = item,
MarkerType = MarkerType.Circle,
};
lineSeries.MarkerResolution = 3;
lineSeries.MarkerFill = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
lineSeries.MarkerStroke = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
lineSeries.MarkerSize = 3;
var points = new List<DataPoint>();
lineSeries.Color = OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
foreach (var price in values[item])
{
points.Add(new DataPoint(price.Week+price.Year, price.Price));
}
if (ButtonsVisibility.Count == 0)
{
lineSeries.IsVisible = (Selected.ProductName == item.ToUpper()) ? true : false;
}
else
{
lineSeries.IsVisible = ButtonsVisibility[colorIndex];
}
lineSeries.ItemsSource = points;
lineSeries.MarkerType = OxyPlot.MarkerType.Circle;
model.Series.Add(lineSeries);
colorIndex++;
}
NumButtons = colorIndex;
LinearAxis yaxis = new LinearAxis();
yaxis.Position = AxisPosition.Left;
yaxis.MajorGridlineStyle = LineStyle.Dot;
model.Axes.Add(yaxis);
LineChart = model;
OnPropertyChanged("GraphModel");
return LineChart;
My doubt is which property I should work with and show at least the value of a concrete point, I have seen the property OnTouchStarted but is only for all the LineSeries and not for a single point. I read in some articles that OxyPlot.Xamarin.Forms include a tracker. I added this line in my code:
lineSeries.TrackerFormatString = "X={2},\nY={4}";
Is supposed to show the x and y values on click but doesn't show anything, any suggestion?
Should show something like that: Tracker info on point
From the following example: Tracker Example
Updated Code
public PlotModel GetLineChart()
{
OnPropertyChanged("GraphModel");
var model = new PlotModel
{
LegendPlacement = LegendPlacement.Outside,
LegendPosition = LegendPosition.BottomCenter,
LegendOrientation = LegendOrientation.Horizontal,
LegendBorderThickness = 0
};
model.PlotType = PlotType.XY;
model.InvalidatePlot(false);
Dictionary<string, List<Prices>> values = HistoricData[Selected.ProductId];
int colorIndex = 0;
List<string> x_names = new List<string>();
foreach (var item in values.Keys)
{
if (item.ToUpper() == Selected.ProductName) { SelectedIndex = colorIndex; }
var lineSeries = new LineSeries()
{
Title = item,
MarkerType = MarkerType.Circle,
CanTrackerInterpolatePoints = false
};
lineSeries.MarkerResolution = 3;
lineSeries.MarkerFill = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
lineSeries.MarkerStroke = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
lineSeries.MarkerSize = 3;
var points = new List<DataPoint>();
lineSeries.Color = OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
foreach (var price in values[item])
{
points.Add(new DataPoint(price.Week+price.Year, price.Price));
}
if (ButtonsVisibility.Count == 0)
{
lineSeries.IsVisible = (Selected.ProductName == item.ToUpper()) ? true : false;
}
else
{
lineSeries.IsVisible = ButtonsVisibility[colorIndex];
}
lineSeries.ItemsSource = points;
lineSeries.MarkerType = OxyPlot.MarkerType.Circle;
lineSeries.TrackerFormatString = "X={2},\nY={4}";
lineSeries.TextColor = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
model.Series.Add(lineSeries);
colorIndex++;
}
NumButtons = colorIndex;
LinearAxis yaxis = new LinearAxis();
yaxis.Position = AxisPosition.Left;
//yaxis.StringFormat = "X={2},\nY={4}";
yaxis.MajorGridlineStyle = LineStyle.Dot;
model.Axes.Add(yaxis);
LineChart = model;
OnPropertyChanged("GraphModel");
return LineChart;
}
}
protected async override void OnAppearing()
{
await _viewModel.LinearViewModel.GetSubCategoryHistoricWeekPrices(App.ViewModel.LoginViewModel.SesionToken, FROM_DATE, TO_DATE);
Plot.Model = _viewModel.LinearViewModel.GetLineChart();
PlotController controller = new PlotController();
controller.UnbindAll();
controller.BindTouchDown(PlotCommands.PointsOnlyTrackTouch);
Plot.Controller = controller;
AddButtons();
}
Xaml Declaration for plot view:
<oxy:PlotView
Grid.Row="2"
Grid.RowSpan="2"
Grid.ColumnSpan="4"
x:Name="Plot" />
Your problem lies with following line.
lineSeries.TrackerKey = "X={2},\nY={4}";
When you use series.TrackerKey, you are specifying that you are using a CustomTracker, which in this case you are not. Custom trackers would be useful if you need to use different trackers for each series in the model.
In you case, you should remove that line and use only TrackerFormatString.
lineSeries.TrackerFormatString = "X={2},\nY={4}";
This would show the tooltip using the format string parameters, where {2} signifies X Value and {4} signifies Y. For your information, following are place holders.
{0} = Title of Series
{1} = Title of X-Axis
{2} = X Value
{3} = Title of Y-Axis
{4} = Y Value
If you need to include additional/custom information in your tool, your Data Point needs to be include that information. This where IDataPointProvider interface becomes handy. You could create a Custom DataPoint by implementing the interface and then you could include the same information in your tooltip as well.
Update Based On Comments
Additionally, to include "Touch", you can specify TouchDown in the PlotController. You can do so by defining the PlotController in your viewModel as following.
public PlotController CustomPlotController{get;set;}
You can define the property as follows.
CustomPlotController = new PlotController();
CustomPlotController.UnbindAll();
CustomPlotController.BindTouchDown(PlotCommands.PointsOnlyTrackTouch);
And in your Xaml
<oxy:Plot Controller="{Binding CustomPlotController}"......

Count number of rows in DataTable that meet some criteria

DataTable dt = GetDataTable();
if(field=="TaskId")
{
string value = ((e.Item as GridFilteringItem)[field] as GridTableCell).Column.CurrentFilterValue
int VALUE = Int32.Parse(value);
int numberOfRecords = dt.Select("TaskId = VALUE").Length;
I want to count the number of rows in a DataTable that have a TaskId == value.
This code is throwing an error saying no column found TaskId[value].
Replace this line
int numberOfRecords = dt.Select("TaskId = VALUE").Length;
WITH
int numberOfRecords = dt.Select("TaskId = " + VALUE).Length;
you passed VALUE within ("")
You could use a simple for loop to iterate each row, looking at the TaskId field of each row. If it matches the criteria, increase a counter.
string value = ((e.Item as GridFilteringItem)[field] as GridTableCell).Column.CurrentFilterValue
int count = 0;
for(int i = 0; i < dt.Rows.Count; i++)
{
if(dt.Rows[i]["TaskId"].ToString() == value)
{
count++;
}
}
Either that or you could use LINQ as well. The rows variable will hold a collection of DataRows that meet your criteria.
var rows = from row in dt.AsEnumerable()
where row.Field<string>("TaskId") == value
select row;
int count = rows.Count<DataRow>();

Dynamically created textbox value in gridview looping issue

In the below code i have created dynamic textbox in grid and i am saving the values in database .In my case there is only two rows created in gridview but in database it is saving 4 rows.Pls help me to solve the issue.
TestSchool.SchoolBusinessLyr.SchoolBizClient Grade = new TestSchool.SchoolBusinessLyr.SchoolBizClient();
System.Collections.Generic.Dictionary<string, string> AssignGrade = new System.Collections.Generic.Dictionary<string, string>();
foreach (GridViewRow row in gdassignmark.Rows)
{
int rowIndex = 0;
for (int i = 0; i < gdassignmark.Rows.Count; i++)
{
//extract the TextBox values
TextBox Sa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtsa");
TextBox fa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtfa");
// var SubjectID = gdassignmark.DataKeys[rowIndex]["SubjectID"] as string;
String cellText = row.Cells[0].Text;
String cellText1 = row.Cells[2].Text;
if (cellText != string.Empty)
{
if (fa.Text == "0")
{
int faval = int.Parse(fa.Text);
int mark = (faval / 40) * 100;
string strmark = mark.ToString();
AssignGrade.Add("BranchID", dpbranch.SelectedValue);
AssignGrade.Add("Academicyear", dpacademicyear.SelectedValue);
AssignGrade.Add("ExamID", dpExamName.SelectedValue);
AssignGrade.Add("ClassID", dpClassName.SelectedValue);
AssignGrade.Add("SectionID", "1");
AssignGrade.Add("SubjectID", cellText.ToString());
AssignGrade.Add("StudentID", dpStudentName.SelectedValue);
AssignGrade.Add("FA", Sa.Text);
AssignGrade.Add("SA", "");
AssignGrade.Add("FAandSA", (strmark));
Grade.InsertStudentGrade(AssignGrade);
}}
You are looping through the Rows twice. Assuming that Rows[i]Cells[i] is correct you can change your code to not loop through all rows for each row:
//foreach (GridViewRow row in gdassignmark.Rows)
//{
int rowIndex = 0;
for (int i = 0; i < gdassignmark.Rows.Count; i++)
{
GridViewRow row = gdassignmark.Rows[i]
//Do your stuff here
}
//}
You are looping over your gridview twice
Remove outer foreach so your code should look like this
TestSchool.SchoolBusinessLyr.SchoolBizClient Grade
= new TestSchool.SchoolBusinessLyr.SchoolBizClient();
System.Collections.Generic.Dictionary<string, string> AssignGrade
= new System.Collections.Generic.Dictionary<string, string>();
for (int i = 0; i < gdassignmark.Rows.Count; i++)
{
//extract the TextBox values
TextBox Sa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtsa");
TextBox fa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtfa");
// var SubjectID = gdassignmark.DataKeys[rowIndex]["SubjectID"] as string;
String cellText = row.Cells[0].Text;
String cellText1 = row.Cells[2].Text;
if (cellText != string.Empty)
{
if (fa.Text == "0")
{
int faval = int.Parse(fa.Text);
int mark = (faval / 40) * 100;
string strmark = mark.ToString();
AssignGrade.Add("BranchID", dpbranch.SelectedValue);
AssignGrade.Add("Academicyear", dpacademicyear.SelectedValue);
AssignGrade.Add("ExamID", dpExamName.SelectedValue);
AssignGrade.Add("ClassID", dpClassName.SelectedValue);
AssignGrade.Add("SectionID", "1");
AssignGrade.Add("SubjectID", cellText.ToString());
AssignGrade.Add("StudentID", dpStudentName.SelectedValue);
AssignGrade.Add("FA", Sa.Text);
AssignGrade.Add("SA", "");
AssignGrade.Add("FAandSA", (strmark));
Grade.InsertStudentGrade(AssignGrade);
}
}

Can a gridview bound to a custom object (CSV file) be sorted?

I have a Datagrid which is getting its data from CSV. No file is sorted in any order, but I want to order the gridview by Username (a field). How could this be done? My XML/gridview code looks like the following:
Streamwriter for writing to csv and populating gridview:
string filename = #"D:\www\isolated\LocalUser\cc-suppressions\generatedsuppressions\surpressions.csv";
StreamWriter sWriter = new StreamWriter(Server.MapPath("Surpression.csv"));
string Str = string.Empty;
string headertext = "";
sWriter.WriteLine(headertext);
int cellLimit = GridView3.Rows[1].Cells.Count;
for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)
{
for (int j = 0; j <= (this.GridView3.Rows[i].Cells.Count - 1); j++)
{
Str = this.GridView3.Rows[i].Cells[j].Text.ToString();
if (Str == " ")
Str = "";
Str = (Str + ",");
sWriter.Write(Str);
}
sWriter.WriteLine();
}
sWriter.Close();
sWriter.Dispose();
}
this.GridView3.DataBind();
You can use the ODBC driver to bind to text data. An example is
http://www.thejackol.com/2004/07/01/connect-to-a-csv-file-using-odbc-c/
You can use a data adapter to populate a DataSet object. Bind to the dataset. You should be able to sort after that.

Resources