Edit a specific row in an asp repeater - c#

I have a repeater and on dataItembound i have something like this
((HtmlTableRow)e.Item.FindControl("prodName")).Visible = false;
This however sets all tablerows in the repeater to be invisible. I would like a specific one to be hidden. Is there a way to do this?
Heres the full imp
protected void RepeaterCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//Get category id
string catId = Request.QueryString["stctid"];
//Call function to check stock levels in the next loaded category
bool stock = checkCategoryStockLevels(catId);
if(stock == true)
{
((HtmlTableRow)e.Item.FindControl("catName")).Visible = false;
((HtmlTableRow)e.Item.FindControl("catImg")).Visible = false;
}
}

In the description you are retrieving the category identifier from the query string of the pages URL. This request will return the same value for all Repeater items and as such every "catName" and "catImg" HtmlTableRow will be hidden.
I assume you wish to hide the rows based on some value stored in the DataSource being bound to the repeater.
To do so you will need to access the DataItem in the ItemDataBound event and perform a check to determine which item requires the row to be hidden.
Below I have bound a List of strings to the Repeater, so I can access each item and perform a check like so, hiding only the HtmlTableRow in the ItemTemplate where the value of the DataItem equals "Item 1":
string dataItem = (string)e.Item.DataItem;
if (dataItem == "Item 1")
{
((HtmlTableRow)e.Item.FindControl("prodName")).Visible = false;
}
I assume you are binding something more complex such as a DataRow or some other Object. Either way the process is the same, cast the DataItem and perform your check.

I would look into using a ListView or a DataList instead, because then you can use data keys to determine row visibility based on a certain value.

I got it.
for (int repeaterCount = 0; count < repeaterID.Items.Count; count++)
{
Label label = (Label)repeaterID.Items[repeaterCount].FindControl("labelID");
label.Text = "Text";
}
Thanks to all that helped

Related

Combobox dropdownlist is not filling from datagridview row

I want when I click on datagridview row then my two text boxes and combobox fill with the corresponding values but two text boxes fill accurately but category dropdown is not filling.
My C# code is
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1 && e.ColumnIndex !=-1)
{
//edit = 1;
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
proID = Convert.ToInt32(row.Cells["proIDGV"].Value.ToString());
proTxt.Text = row.Cells["nameGV"].Value.ToString();
barcodetxt.Text = row.Cells["barcodeGV"].Value.ToString();
catDD.SelectedValue = row.Cells["catIDGV"].Value.ToString();// not working properly due to which edit button is not working
// catDD.SelectedItem = row.Cells["catGV"].Value.ToString();//Also Write this line of code but not produce the desire result
MainClass.Disabled(leftPanel);
}
}
For category dropdown, which is a combo-box, to have a SelectedItem or SelectedValue you should already have all the possible categories in the "items" property, otherwise, the programming cannot select the category out of nowhere. To select items which don't exist you need to add an item first, or if you don't really need the items afterward you can just use:
catDD.Text = row.Cells["catIDGV"].Value.ToString();
Although I would not recommend doing it this way.
The other way is that you can add items by doing this (this is what I recommend):
Edit: You first add the item then select it.
string item = row.Cells["catIDGV"].Value.ToString(); // Your selected item in DataGridView
catDD.Items.Add(item); // Add the item
catDD.SelectedItem = item; // Select the item

Remember the check-box option in a GridView while paging and looping through entire GridView

I have a gridview on a aspx page with pagination enabled. this gridview contains some data fields from a database and a check-box for each row.
Now, I read on this post: loop all gridview rows on button click when paging enabled that to be able to loop through all the rows on all the pages of the gridview, I have to disable the pagination, rebind the gridview, loop through all rows, re-enable the pagination and finally rebind the gridview.
I started out wondering whether the check-box option will be remembered if I rebind the datasource before looping through all the rows, but quickly determined that even going from one page to the next page then back again the check-box option is lost.
I need to have a gridview with pagination and a check-box on each row, then loop through the entire gridview on the click of a button and do some action depending on the check-box option.
Its not possible with the GridView natively. But there are many methods to simulate the same behaviour. One method will be to handle the issue on the PageIndexChanging event like this.
protected void OriginalTable_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
var selectedIDs = (Session["CheckedIDs"] != null) ?
Session["CheckedIDs"] as List<int> : new List<int>();
//we are now at current page. set the checked ids to a list
foreach (GridViewRow row in OriginalTable.Rows)
{
//get the checkbox in the row ( "HasEmail" is the name of the asp:CheckBox )
var emailCheckBox = row.FindControl("HasEmail") as CheckBox;
//gets the primary key of the corresponding row
var rowOrgID = Convert.ToInt32(OriginalTable.DataKeys[row.RowIndex].Value);
//is row org_id in the selectedIDs list
var isRowIDPresentInList = selectedIDs.Contains(rowOrgID);
// add to list
if (emailCheckBox.Checked && !isRowIDPresentInList)
{
selectedIDs.Add(rowOrgID);
}
//remove from list
if (!emailCheckBox.Checked && isRowIDPresentInList)
{
selectedIDs.Remove(rowOrgID);
}
}
OriginalTable.PageIndex = e.NewPageIndex;
BindTable();
//we are now at the new page after paging
//get the select ids and make the gridview checkbox checked accordingly
foreach (GridViewRow row in OriginalTable.Rows)
{
var emailCheckBox = row.FindControl("HasEmail") as CheckBox;
var rowOrgID = Convert.ToInt32(OriginalTable.DataKeys[row.RowIndex].Value);
if (selectedIDs.Contains(rowOrgID))
{
emailCheckBox.Checked = true;
}
}
Session["CheckedIDs"] = (selectedIDs.Count > 0) ? selectedIDs : null;
}
Here we are using Session to maintain the values across pages. As an added advantage you will get the checked values in any other event by accessing the session variable.
Update
If you already have pre-populated HasEmail field, do this to set the values at initialization
private void BindTable()
{
DataTable table = GetTableFromDatabase();
var selectedIDs = table.AsEnumerable()
.Where(r => r.Field<bool>("HasEmail"))
.Select(r => r.Field<int>("ORG_ID"))
.ToList();
if (selectedIDs != null && selectedIDs.Count > 0)
Session["CheckedIDs"] = selectedIDs;
OriginalTable.DataSource = table;
OriginalTable.DataBind();
}

Changing other columns value onselectedvaluechanged event in combobox in XtraGridView

Is there a way to get handle of row of which the selectionvalue is changed in combobox?
Let me try to explain it using example.
In GridView, I have two columns,
Name, Type
Type column has combobox, with values 1 and 2.
What I want to do is on selecting value 1 in type column ,
I want to change the Name to "One"
On selecting 2 in type column,
I want to change the Name to "Two"
This is what I was trying,
private void OnType_SelectedValueChanged(object sender, EventArgs e)
{
DevExpress.XtraEditors.ComboBoxEdit comboType = sender as DevExpress.XtraEditors.ComboBoxEdit;
DataRow row = (DataRow) myGridView.GetFocusedRow();
if (comboType .SelectedItem.ToString() == "1")
{
row.Name = "one";
}else
{
row.Name = "two";
}
}
But here I am getting myGridView.GetFocusedRow() as null.
What am I doing wrong?
Correct way is to bind a repository editor to column.
RepositoryItemComboBox riCmb = new RepositoryItemComboBox();
Handle the editvaluechanged event
riCmb.EditValueChanged += riCmb_EditValueChanged;
Then inside the event handler
if(myGridView.GetRowCellValue(myGridView.FocusedRowHandle, "FieldName").ToString() == "1")
{
grvInstruments.SetRowCellValue(grvInstruments.FocusedRowHandle, "FieldName", "One");
}

How can I access the last item in a DataList in order to set its class?

I need to create buttons for each item in a DataList, but the last button needs to be formatted differently, so it needs a different css class applied to it.
I think this should be done in the OntemDataBound method, but feel free to correct me if I'm wrong.
I want to do something like this:
protected void dlDataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemIndex == dlDataList.Items.Count - 1) //This doesn't work like I'd hoped
{
Panel button = (Panel)e.Item.FindControl("btnButton");
button.CssClass = ("altClass");
}
...
}
The problem is, I don't think the datalist knows how many items it will have in the ItemDataBound event because dlDataList.Items.Count is always the same as the ItemIndex.
Any ideas on how I can give the last button the altClass css class?
Before you bind the DataList, save the total number of items in a page level variable. Then on your ItemDataBound, check to see if the current index is equal to the total items (-1 of course) and set your css class accordingly
Usually index are zero based, so in a list with 5 elements the index of the last element will be 4 and the count 5 so if you subtract 1 from the count I think it will work
for (int i=0; i<= DataList1.Items.Count; i++)
{
if (e.Item[i] == dlDataList.Items.Count - 1) //This doesn't work like I'd hoped
{
Panel button = (Panel)e.Item.FindControl("btnButton");
button.CssClass = ("altClass");
}
}
You need to query the DataList's DataSource instead of it's items since the items are created just before they are databound.
protected void dlDataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// use the item's DataItem property or the DataList's DataSource property directly
DataTable tbl = ((DataRowView)e.Item.DataItem).Row.Table;
if (e.Item.ItemIndex == tbl.Rows.Count - 1)
{
// ....
}
}
}
The ItemDataBound event is being fired for every object in your data source. So every time an item is added to the data list it's index is 1 higher but also your count, so they are equal constantly. You should do your comparison with the data list data source property and get a count from that. The data source has predetermined knowledge of how big your list will be. You just need to cast the data source as an object that it is data bound to.
So if it is a List<string> you would use something like:
if (e.Item.ItemIndex == ((List<string>)dlDataList.DataSource).Count - 1)

Assigning Values to DropDownList in Grid

I have a DropDownList in a Grid and I have a foreach loop that loops through a Query and matches data and fills the drop down list for each row on that. But It is putting the data all in the same dropdownlist. So row 1, row 2, row 3, etc. all get combined into the dropdownlist. I am trying to make it so in row 1 dropdlownlist has the info for row 1 and row 2 the dropdownlist has the info for row 2 and so on.
I have this so far:
protected void grdExceptions_ItemDataBound(object sender, GridItemEventArgs e)
{
var linqContext = new DataClassesDataContext();
var sessionleads = from q in linqContext.Leads where q.SessionID == SessionId orderby q.RowIndex select q;
if (e.Item is GridDataItem)
{
foreach(var p in sessionleads)
{
var lQuery = (from a in gServiceContext.CreateQuery("account") where (a["name"].Equals(p.AccountName) &&
a["address1_postalcode"].Equals(p.ZipCode) &&
a["address1_stateorprovince"].Equals(p.State)) ||
(a["address1_line1"].Equals(p.Address1) &&
a["address1_postalcode"].Equals(p.ZipCode) &&
a["address1_city"].Equals(p.City))
select new
{
Name = !a.Contains("name") ? string.Empty : a["name"]
});
foreach (var a in lQuery)
{
((e.Item as GridDataItem)["Account"].FindControl("AccountList") as DropDownList).Items.Add(new ListItem(a.Name.ToString()));
}
}
}
}
I have a DropDownlist in the ItemTemplate of the Grid. So for the first row I would want whatever matches are found assigned to the drop downlist in the first row, for the second row I would want whatever matches the dropdownlist in the second row, etc.
What am I doing wrong?
Thanks!
It seems like you're expecting SessionId to somehow be different when ItemDataBound fires for each new row, but it's just staying the same. Do you have some other filter criteria you could add to your where clause? Or some way to update SessionId for each new row?

Categories

Resources