FindControl and Get Selected Value of Dropdown - c#

This scenario is occurring when using C# code behind to find HTML Controls added dynamically from SQL Data Results.
Using the following there is an iteration though the Table rows and row each table row, we write the Controls value, in this case a HtmlSelect. The Html Select Element is in Cell 3
for (int i = 1; i <= Table1.Rows.Count - 1; i++)
{
HtmlSelect select = Form.FindControl("MainContent_selectBoxstatus" + i) as HtmlSelect;
System.Diagnostics.Debug.Write(select.Value);
}
Resulting in:
A first chance exception of type 'System.NullReferenceException'
occurred in project.dll
If i use the following:
for (int i = 1; i <= Table1.Rows.Count - 1; i++)
System.Diagnostics.Debug.Write(Table1.Rows[i].Cells[0].Text);
I get the desired result, of the text from Cell 1.
How the Select Dropdown is created:
for (int i = 0; i < dr.FieldCount; i++)
HtmlSelect sStatus = new HtmlSelect();
sStatus.Items.Add(new ListItem("Working", "0"));
sStatus.Items.Add(new ListItem("Fault", "1"));
sStatus.SelectedIndex = 0;
sStatus.Attributes.Add("class", "dropdownlist");
sStatus.ID = "selectBoxstatus" + rowindex;
cell.Controls.Add(sStatus);

That's what usually happens when you are trying to "hack" ASP.NET internals. I mean "hack" because using magic strings to resolve the auto-generated ids assigned to child controls is extremely unsafe. There are much better and safer ways to do this.
1- If you want to render a tabular layout, I'd strongly recommend using a databound control such as a GridView, ListView, etc where you can intersect its RowDatabound event and retrieve the child controls in a safe manner
2- If you can't afford to do a re-write then replace your code as follows...
for (int i = 0; i < Table1.Rows.Count; i++)
{
HtmlSelect select = Table1.Rows[i].Cells[0].FindControl(string.Format("selectBoxstatus{0}", i)) as HtmlSelect;
if(select != null)
System.Diagnostics.Debug.Write(select.Value);
}
Option 2 Code Analysis
for (int i = 0; i < Table1.Rows.Count; i++)
Nitpicking, but initializing i to 0 this makes it easier to read...believe it
HtmlSelect select = Table1.Rows[i].Cells[0].FindControl(string.Format("selectBoxstatus{0}", i)) as HtmlSelect;
I'm not too sure what Form meant in your original post but it makes more sense to use the object you're iterating....Table1 rows collection. I also refer to Cell[0] which is the first cell in the iteration's current row(feel free to adjust it)...this is still not safe but it's the only way to achieve it in the current scenario, if you need more code safety, then resort to option one. Also notice that FindControl doesn't mess around with auto-generated id, it simply uses the actual Id specified for the child control
if(select != null)
After you attempt to retrieve the select control make sure to check whether the control was successfully retrieved or not.
Hope it makes sense

Try changing your loop so that you call findcontrol on the row instead:
for (int i = 1; i <= Table1.Rows.Count - 1; i++)
{
HtmlSelect select = Table1.Rows[i].FindControl("MainContent_selectBoxstatus" + i) as HtmlSelect;
}

Related

Finding a cell in devexpress datagrid

I'm new to DevExpress GridControl.
I need to find a particular cell in the grid and then do something with it's value.
How do I go about this please?
In the grid's Loaded method, I tried using myGrid.FindRowByValue("ProductType","ABC"), but always gives a negative number.
Thanks.
Here is code you can try
for (int i = 0; i < gridView1.DataRowCount; i++) {
object b = gridView1.GetRowCellValue(i, "FieldName");
if (b != null && b.Equals(<someValue>)){
gridView1.FocusedRowHandle = i;
return;
}
}
you can go to this link for more details.
https://www.devexpress.com/Support/Center/Question/Details/Q132599/get-row-by-cell-value
Unlike XtraGrid, the DXGrid for WPF does not provide the DataRowCount property - that is why we suggested checking the GridControl's ItemsSource. On the other hand, our grid has the VisibleRowCount property, which will be useful in some scenarios.
To accomplish this task, iterate through visible grid rows manually as shown below.
void MoveFocusToLast(GridControl grid, string fieldName, object value) {
for (int i = grid.VisibleRowCount - 1; i >= 0; i--) {
var handle = grid.GetRowHandleByVisibleIndex(i);
var currentValue = grid.GetCellValue(handle, fieldName);
if (currentValue != null && currentValue.Equals(value)) {
grid.View.FocusedRowHandle = handle;
return;
}
}
}
Grid also provides the FindRowByValue method, which allows you to
find a row by a specific cell value. This method returns the handle of
the corresponding row, and you can make that row visible by setting
the FocusedRowHandle property or calling ScrollIntoView. I
have prepared a sample demonstrating this approach.
See Also:
Traversing Rows
Find Row
Get RowHandle from a cell value

c# : How ot create a grid row array programatically

I am working in c# and i am under a situation where i have a grid (childGrid) and inside this grid i want to create 3 more grids dynamically.
I want to achieve it using arrays. My try to do this is:
Grid[] row = new Grid[counts]; //counts=3 in my case but decde dynamically.
for (int i = 0; i < counts; i++)
{
row[i].RowDefinitions.Add(new RowDefinition());
}
I do so because i have one childGrid (parent grid) on that i will have 3 containers (3 more grid as container as child of chidGrid) so it is row[i] in my case (for i :0 to <3) (if you see the code). and on row[0]. i have a checkbox and two different UIelements at row[1 & 2] . I take different containers because if i select the check of row[0](checkbox) it will set the opacity of row[1].opacity=0.5; and on unchecking it will do row[2].opacity=0.5;. So thats why i have different 3 grids container on a grid.
the line row[i].RowDefinitions.Add(new RowDefinition()); gives warning.
The object reference is not set to an instance of an object.
How to achieve this ? I can not do statically because i dont know statically the value of counts(which i assumed 3 here)
You didn't actually create any grids before you tried to add rows to them.
Grid[] row = new Grid[counts];
for (int i = 0; i < counts; i++)
{
row[i] = new Grid();
row[i].RowDefinitions.Add(new RowDefinition());
}
If I interpret your question correctly, the proper way to set all the rows to a default value is not to add them, but to set them.
for (int i = 0; i < counts; i++)
{
row[i].RowDefinitions[counts] = new RowDefinition();
}

sum values which are loaded in gridview

How can I plus all values of one selected row of a gridview in C# asp.net application?
For example I have a gridview in which is only one row. Values of this row are only number. So I want to plus this numbers.
I tried this loop but it writes all gridview numbers(it isn't summing them).
for (int i = 2; i < GridView1.Columns.Count; i++)
{
int x = 0;
x += int.Parse(GridView1.Rows[0].Cells[i].Text);
Response.Write(x.ToString());
}
I think you should approach this from a different perspective. The GridView is just a display control and doesn't 'hold' the data it is displaying. You are trying to use data that it really doesn't contain using a 'screen scrape' approach. You should be looking to the DataSource you bound to the grid in the first place and using the data there.
For example:
List<YourObjectWithTheNumbers> lst = something;
yourGridView.DataSource = lst;
ViewState["YourData"] = lst; // you could use Session instead: Session["YourData"]
So at this point your data is bound and saved for later use so now just update your numbers and rebind to the GridView again:
List<YourObjectWithTheNumbers> lst =
(List<YourObjectWithTheNumbers>)(ViewState["YourData"]);
int rowTotal = 0;
rowTotal += lst[0].Field1;
rowTotal += lst[0].Field2;
//etc...
yourLiteral.Text = rowTotal.ToString();
At this point you are using the actual data, not pulling it out of the grid that should be used for display purposes. It's also more secure in that you can keep the data source securely stored on the server if necessary (don't use ViewState if this is a concern) so that it can't be manipulated.
In HTML GridView render as table , better you can use Jquery to add the values ,
var total=0;
$('#gridview1').find('tr td').each(function(i, td){
var data= parseInt( $(td).val());
total+=data;
});
I created method in which I had loop and it worked !!!!!!!
public int Sum()
{
int z = 0;
int i;
int x = 0;
for (i = 0; i < GridView1.Columns.Count; i++)
{
x += int.Parse(GridView1.Rows[0].Cells[i].Text);
}
return x;
}
It was #N4TKD idea. Thanks to you !!!!

Finding an item in asp.ListView with Value when paging is enabled

I'm trying to find the selected Item in an aspx ListView that is on a separate page, then switch the page and select the item. I have the value property of the ListViewItem I am looking for, but cannot seem to get it to work. Here is what I tried:
for (int i = 0; i < lvProject.Items.Count; i++)
{
if (((Label)lvProject.Items[i].FindControl("Project_IDLabel")).Text == project.ToString())
{
lvProject.SelectItem(i);
break;
}
}
So lvProject is my list view. The project Variable is an Int64 which represents the UID of my Project. This is also the Value of my ListViewItems. The problem with the code above is that when paging is enabled, and the item is on a different page this will not work because the listView.Items.Count is set to the # of Items on the current page only.
My goal is to find the item, set the listview to display the correct page, and finally select the item. You would figure that I could just set the SelectedValue property, but this is not that simple as it is read only. Any ideas would help greatly, thanks in advance.
--Roman
In order to get the total record count from the object data source, you should use the Selected event as follows:
protected void ObjectDataSource1_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
// Get total count from the ObjectDataSource
DataTable dt = e.ReturnValue as DataTable;
if (dt != null) recordCount = dt.Rows.Count; // recordCount being declared outside the method
}
You would then be able to search for the item as follows:
for (int i = 0; i < recordCount; i++)
{
Label lblItem = (Label)lvProject.Items[i].FindControl("IdLabel");
if (lblItem.Text.Equals(itemToSearch))
{
lvProject.SelectedIndex = i;
break;
}
}
Hope it helps!
How do you bind ListView Items?
If you are using database level paging (stored procedure, query) - you should do search in the same way - using database query/stored procedure by passing a search criteria.
If you are bind ListView Items to a collection of items which are provided by a business/data layer - you have to create search method on layer which provides items so this method will be able to loop through the items.
You should set the SelectedIndex property to i
for (int i = 0; i < lvProject.Items.Count; i++)
{
if (((Label)lvProject.Items[i].FindControl("Project_IDLabel")).Text == project.ToString())
{
lvProject.SelectedIndex = i;
break;
}
}

Full text search on a bound DataGridView control

I cannot seem to be able to find a way to do a full text search on a databound DataGridView control across the entire breath of its columns and rows.
The DataTable and DataView objects seems to force me into searching for specific columns either through Select(), Find(), or FindRows(). Same with the DataGridView control.
I have one search string and I need to run it against the whole contents of the DataGridView. I'm sure the answer lies somewhere close. But I cannot seem to be able to find it at this stage in my apprenticeship of C# and the .Net framework.
This is my current solution which I would like to avoid:
/*...*/
for (int i = found_last_row + 1; i < dataGridRes.Rows.Count; ++i)
{
for (int j = 0; j < dataGridRes.Columns.Count; j++)
{
if(dataGridRes.Rows[i].Cells[j].Value.ToString().Contains(search_last_str.))
{
dataGridRes.Rows[i].Selected = true;
dataGridRes.FirstDisplayedScrollingRowIndex = i;
found_last_row = i;
break;
}
}
}
/* ...*/
I think the common approach is to search the source data (not the grid), then re-bind to only show the matches. If you use paging, the grid pulls the data page by page from the database, so you would only be searching the page that you currently see.

Categories

Resources