How do I change a ListView dynamically on DataBound? - c#

I have a ListView with a template, it puts a bunch of data in, like X Y Z.
I want to hide show some columns based on criteria, so I have ItemDataBound event, but I don't know how to get the actual listview row so I can do things to do it.
Any ideas?

You can access the ListViewItemEventArgs' Item property to get at the current item (the one being bound to data).
The sample code below (which shows how to customize a ListView item in the ItemDataBound event) was taken from the MSDN documentation:
protected void ContactsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
Label EmailAddressLabel;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
// Display the e-mail address in italics.
EmailAddressLabel = (Label)e.Item.FindControl("EmailAddressLabel");
EmailAddressLabel.Font.Italic = true;
System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;
string currentEmailAddress = rowView["EmailAddress"].ToString();
if (currentEmailAddress == "orlando0#adventure-works.com")
{
EmailAddressLabel.Font.Bold = true;
}
}
}

Related

How to get current row of datagridview values when clicking on button?

I have a View Model in which my data is stored to be used on the presenter and window. However, I now need to get (when pressing a button) the current row's results on the grid into my view model. I first used the mouse double click event, but the requirements changed from that to a button on the form:
private void dgvResults_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (this.colOrderNo.Index != e.ColumnIndex || e.RowIndex < 0) return;
var auditOrder = (PurchaseOrdersTrackingViewModel) this.dgvResults.Rows[e.RowIndex].DataBoundItem;
this.AuditOrderKey = $"{auditOrder.OrderNo}|{auditOrder.ItemNo}|{auditOrder.WarehouseId}|{auditOrder.ItemSequence}";
}
That's my old code. Now I need that here:
private void btnAuditLog_Click(object sender, EventArgs e)
Not sure how to refer to the RowIndex without the DataGridViewCellMouseEventArges event. I tried the CurrentRow property, but it doesn't do the job.
Just another question on the fly, if someone could assist with that as well, how do I get a value from one form to another, spesifically a properties value. It's not on the grid, in a control. It's basically just public string order that's all. I set the value on one form, then need it for query filtering on another. Let me know if you need anything else.
You want to use the SelectedRows property of the DataGridView. It tells which row is selected. In this case, you seem to want the first selected row (since you have a single property called this.AuditOrderKey).
The column order no to longer matters in this context.
if (dgvResults.SelectedRows.Count == 0) return;
var auditOrder = (PurchaseOrdersTrackingViewModel) dgvResults.SelectedRows[0].DataBoundItem;
this.AuditOrderKey = $"{auditOrder.OrderNo}|{auditOrder.ItemNo}|{auditOrder.WarehouseId}|{auditOrder.ItemSequence}";
If you don't have selected rows, CurrentRow is an option:
if (dgvResults.CurrentRow == null) return;
var auditOrder = (PurchaseOrdersTrackingViewModel) dgvResults.CurrentRow.DataBoundItem;
this.AuditOrderKey = $"{auditOrder.OrderNo}|{auditOrder.ItemNo}|{auditOrder.WarehouseId}|{auditOrder.ItemSequence}";
Use the SelectedRows property of the DataGridView. Assuming that you set your DataGridView as MultiSelect = false; and SelectionMode = FullRowSelect;
if (dgvResults.SelectedRows.Count > 0)
{
dgvResults.SelectedRows[0].Cells["yourColumnName"].Value.ToString();
}
In your button click event, it will look like this. (Assuming that your button name is btnEdit)
private void btnEdit_Click(object sender, EventArgs e)
{
if (dgvResults.SelectedRows.Count > 0)
{
string selectedValue = dgvResults.SelectedRows[0].Cells["yourColumnName"].Value.ToString();
}
}

Telerik RadGrid- Access Items' GroupFooter

I'm trying to write content to an items' Group Footer on an item's ItemDataBound event.
Anyone have any idea how to access an Item's group footer from the Item itself?
In other words, how would I get an item's associated group footer from the item object as it's being bound?
protected void grid_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = (GridDataItem)e.Item;
**GridItemGroupFooter footer = item.GroupFooter** <-- Pseudocode for what I want to do
}
}
you should do it like this
if (e.Item is GridFooterItem)
{
itemtype somenameforitem=(itemtype )grid.FooterRow.FindControl("youritemid");
//for ex if you need textbox then it will be like this
//TextBox texte=(TextBox)gridname.FooterRow.FindControl("textboxid");
}
also you can do it like this.
GridFooterItem footerItem = (GridFooterItem)grid.MasterTableView.GetItems(GridItemType.Footer)[0];
TextBox texte=(TextBox)footerItem.FindControl("textboxid");//accessing Button inside FooterTemplate
I have give the index [0] while getting the grid footer item as the text box is one and only item in my grid footer, if you have multiple footer items, you can give the index of the item you wan to find

Hide DataList row based on value from web service

I am retrieving a set of value from a web service and populating a dataList with those values-
ActiveDataList.DataSource = ws.TermsReturnActive(sql);
ActiveDataList.DataBind();
How can I hide a particular column of the dataList depending on the value,
e.g.
if(value == 1)
{
//Hide Column
}
This action however would have to hide the same row of another dataList in parallel to it.
I can modify a cell on this second dataList using by retrieving the value from the first as so -
TextBox tb1 = (TextBox)sender;
DataListItem item1 = (DataListItem)tb1.NamingContainer;
TextBox txt1 = (TextBox)tData.Items[item1.ItemIndex].FindControl("tTextBox");
string term = txt1.Text;
So if I can retrieve a value from a separate dataList row, I was thinking I would also be able to adjust its visability.
How can I achieve this as the web service call is done in the page load so I believe it would have to be done when the dataList item is bound?
if iam right, you should have something like this in your aspx-file right?:
<asp:DataList ID="DataList1" runat="server" OnItemDataBound="DataList1_ItemDataBound"></asp:DataList>
As you can see you should add a "OnItemDataBound" Event where you can check your value and hide a item, if you want.
So you can react like this and hide some items:
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
TextBox tbCurrentTextBox = (TextBox)e.Item.FindControl("tTextBox");
if (DataList1.Items[e.Item.ItemIndex].ToString() == "1")
{
e.Item.Visible = false;
}
}
}

DataGridViewCombBoxColumn cell value and different dropdown list

I've a very trivial requirement which makes me go nuts. I've a DataGridView in windows forms application. This contains one databound ComboBox Column. I'm using DisplayMember and ValueMember properties of that combobox.
Now my requirement is ComboBox should show the list of DisplayMembers in drop down list but when user selects one item from it, I should display the part of that DisplayMember in the combobox cell visible to the user. For example.
My display member list looks as below:
"Cust1 - Customer 1"
"Cust2 - Customer 2"
"Cust3 - Customer 3"
and when user selects any one of them from the above list (Say user selected 'Cust2 - Customer 2') then I need to display the value in the combobox column cell as only "Cust2" instead of complete DisplayMember text.
This DisplayMember list is a combination of two fields from the datasource bound to it i.e. First part points to CustomerCode field and second part points Customer name. I need to display only CustomerCode in the ComboBox cell after user selects one item from the drop down list.
How can I do this? Or should I come up with my own control which will have a different AutoCompleteCustomSource and display member value. Even I'm confused with that approach too.
Update: As no one has come up with any solution to my problem. Now I'm starting a bounty for that, also if anyone can suggest me other way to implement the same functionality, it would be great.
I've even tried to come up with my own control and tried to work on simple combobox to display a different value than the selected dropdown list, even that didn't work. Is there any other way to implement this? Any tips and tricks are greatly appreciable.
#Anurag: Here is the code which I've used.
Created a datagridview in the design mode. Created one column of type 'DataGridViewComboBoxColumn' that and named it as CustomerColumn.
In the designer file it looks like below:
private System.Windows.Forms.DataGridViewComboBoxColumn CustomerColumn;
This is the entity class which I've used for datasource
public class Customer
{
public int Id { get; set; }
public string CustCode { get; set; }
public string CustName { get; set; }
public string NameWithCode { get; set; }// CustCode - CustName format
}
In the form load event I'm doing the following:
CustomerColumn.DataSource = GetCustomers();
CustomerColumn.DisplayMember = "NameWithCode";
CustomerColumn.ValueMember = "Id";
I'm answering my own question because I've implemented my own solution to this by using custom control.
This custom control is created by keeping a textbox above combo box in such a way that only drop down button of combobox is visible.
Now I've created a custom column in datagridview deriving the DataGridViewEditingControl from my usercontrol.
I've added a property in Usercontrol which will take drop down list source from the control which is hosting datagridview.
Now in the EditingControlShowing event I'm setting this property as below
private void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if(dataGridView2.CurrentCell.ColumnIndex.Equals(0) && e.Control is UserControl1)
{
var uscontrol = e.Control as UserControl1;
uscontrol.DropDownListSource = source;
}
}
This drop down list source is used in the usercontrol to set the autocompletesource to the textbox and datasource to the combobox as below:
Whenever I set the DropDownDataSource I'm firing an event in the usercontrol which will do the following. This is to ensure that every time EditingControlShowing event occurs for this column in DataGridView, this source is updated for textbox and combobox in usercontrol.
private void DropDownSourceChanged(object sender, EventArgs eventArgs)
{
textBox1.AutoCompleteCustomSource = DropDownListSource;
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
comboBox1.DataSource = DropDownListSource;
}
Now whenever user starts typing in the textbox autocomplete source will display dropdown list with 'NameWithCode' values and if user selects one of them then I'll set it to the Text propery overidden in my usercontrol which will be used for the cell value in the DataGridView. Now based on the Textbox text (which is NameWithCode) I can get the code part and set it to the text property.
If user uses combobox dropdown button to select the item then I'll get the combobox selected text and set it in the Textbox which is ultimately used by the cell for getting value.
This way I could achieve the solution I want.
#Homam, solution also works but when I change the ComboBox's DropDownStyle to allow the user to type the value in the combobox it behaves weirdly and not getting up to the mark solution for my requirement. Hence I used this solution.
I know that this is not perfect solution, but I looked for a better one and I didn't find, so I went to a workaround
I did the following:
when the user open the ComboBox, I change the DisplayMember to "NameWithCode"
when the user close it, I return it to "CustCode"
You can Access to the ComboBox control by DataGridView.EditingControlShowing event for the DataGridView.
The code:
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
var comboBox = e.Control as ComboBox;
comboBox.DropDown += (s1, e1) => comboBox.DisplayMember = "NameWithCode";
comboBox.DropDownClosed += (s2, e2) =>
{
// save the last selected item to return it after
// reassign the Display Member
var selectedItem = comboBox.SelectedItem;
comboBox.DisplayMember = "CustCode";
comboBox.SelectedItem = selectedItem;
};
}
Note: You have to start the DisplayMember with "CustCode"
Good luck!
Each time at the offensive of event dataGridView1_EditingControlShowing there is addition of new handlers for events comboBox.DropDown and comboBox.DropDownClosed. It results in the increase of number of these handlers and their repeated calls. This code decides this problem.
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
var comboBox = e.Control as ComboBox;
comboBox.DropDown += comboBox_DropDown;
comboBox.DropDownClosed += comboBox_DropDownClosed;
}
private void comboBox_DropDown(object sender, System.EventArgs e)
{
var comboBox = sender as ComboBox;
if(comboBox != null)
{
comboBox.DropDown -= comboBox_DropDown;
comboBox.DisplayMember = "NameWithCode";
}
}
private void comboBox_DropDownClosed(object sender, System.EventArgs e)
{
var comboBox = sender as ComboBox;
if(comboBox != null)
{
comboBox.DropDownClosed -= comboBox_DropDownClosed;
var selectedItem = comboBox.SelectedItem;
comboBox.DisplayMember = "CustCode";
comboBox.SelectedItem = selectedItem;
}
}

Why won't my ListView SelectedItemTemplate show when selected?

I have a databound ListView in asp.Net. I have both ItemTemplate and SelectedItemTemplate used in the aspx page.
In the .cs page I have this. I have verified by stepping through the code that the if statement evaluates to true only when it is supposed to, and that the selected index is set. However the HTML output is as if all items use the ItemTemplate.
int indexCounter = 0;
protected void lvProducts_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
if (((DataRowView)e.Item.DataItem)["ID"].ToString() == Request.QueryString["id"])
{
lvProducts.SelectedIndex = indexCounter;
}
indexCounter++;
}
}
Is there a better way to do this?
check out this post
"Setting the SelectedIndex anywhere after DataBinding works, you just don't get the SelectedItemTemplate. For that you have either rebind the data; or reinstantiate the SelectedItemTemplate on the ListViewItem. be sure to clear the ListViewItem.Controls collection first!"

Categories

Resources