I want to add a button on GridView cell on certain condition.
I did the following in RowDatabound event
if( i==0)
{
Button btn= new Button();
btn.Text = "view more";
e.Row.Cells[7].Controls.Add(btn);
}
When this executes, the text in the cell which is bound is lost and only the button appears.
I need to have the button along with the cell text present already.
Can anyone please help me doing this?
When you add a control into the cell it trumps the text in the cell and only wants to display the control(s).
You can however have both the text and the button while keeping them separate. To do this you need to add another control in the form of a label:
Label myLabel = new Label();
myLabel.Text = e.Row.Cells[7].Text; //might want to add a space on the end of the Text
e.Row.Cells[7].Controls.Add(myLabel);
LinkButton myLinkButton = new LinkButton();
myLinkButton.Text = "view more";
e.Row.Cells[7].Controls.Add(myLinkButton);
It's a workaround, check if it helps you:
You can convert your existing BoundColumn to Linkbuton if it is feasible with your requirement.
if( i==0)
{
LinkButton lnkbtn = new LinkButton();
lnkbtn.Text = e.Row.Cells[7].Text;
// Create a command button and link it to your id
// lnkbtn.CommandArgument = e.Row.Cells[0].Text; --Your Id
// lnkbtn.CommandName = "NumClick";
// btn.Text = "view more";
e.Row.Cells[7].Controls.Add(lnkbtn);
}
You have to recreate all dynamic controls on every postback. But RowDataBound is executed only if the grid gets databound. So this is not the right approach.
If this is just a single button you should add it declaratively to the aspx in a TemplateField. Then you can switch visibility in RowDataBound.
Tutorial 12: Using TemplateFields in the GridView Control
Button btn = (Button)e.Row.FindControl("ButtonID");
btn.Visible = i==0;
You can handle the Click event of the Button for your "view more"-logic.
Related
I've RadGrid where I want to add a column dynamically so I've done something like this in page load
GridTemplateColumn gtc = new GridTemplateColumn();
gtc.DataField = "chqNumber";
gtc.HeaderText = "Cheque Number";
gtc.UniqueName = "chqNumber";
RadGrid1.MasterTableView.Columns.Add(gtc);
It work fine, now I want to add textbox in this column as the user click "+add new record" on grid here is my code of itemCreated event
GridEditableItem gdit = (GridEditableItem)e.Item;
RadTextBox txtBox = new RadTextBox();
txtBox.ID = "someIDWhatEver";
gdit["chqNumber"].Controls.Add(txtBox);
but this textbox gets added to another new column what I mean is this textbox does not added to same chqNumber column you can view my attached image which will illustrate better
as you can see my dynamic column gets added at the last even after insert and cancel button and dynamic textbox doesn't gets in this column please avoid my english grammatical mistakes :P
I am highlighting a certain LinkButton within my DataList when the linkbutton is pressed. Each row has a link button, and when the user presses the next link button from any of the rows, the previous highlighted link button should get the normal transparent background.
For highlighting, I am using the following:
protected void DataList_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "select")
{
LinkButton highlighted = ((LinkButton)(e.Item.FindControl("Item")));
highlighted.BackColor = System.Drawing.Color.Yellow;
...
}
How do I 'un-highlight' the previous link button, when the user choose any other link button from the data list?
Since the post back are taking place, I can't have a global LinkButton variable to check the next time to store the previously clicked LinkedButton.
Any suggestions?
If you are rebinding the grid on page load, the color of the LinkButtons should be reset. However, something like this should be able to set the background color of all linkbuttons to transparent:
VB.NET:
For Each DLItem As DataListItem In DataList1.Items
Dim unHighLight As LinkButton = DLItem.FindControl("Item")
If Not unHighLight Is Nothing Then
unHighLight.BackColor = System.Drawing.Color.Transparent
End If
Next
Dim highlighted As LinkButton = e.Item.FindControl("item")
highlighted.BackColor = System.Drawing.Color.Yellow
C#:
foreach (DataListItem DLItem in DataList1.Items)
{
//unhighlight all ilnkbuttons
LinkButton unHighLight = ((LinkButton)(DLItem.FindControl("Item")));
if (unHighLight != null)
{
unHighLight.BackColor = System.Drawing.Color.Transparent;
}
}
LinkButton highlighted = ((LinkButton)(e.Item.FindControl("Item")));
highlighted.BackColor = System.Drawing.Color.Yellow;
How do you add a button to cells in a row and not the entire column in a datagridview?
I think Adrian's answer was close. Try something like this.
if ((string)table.Rows[0].Cells[0].Value == "I should be a button") {
// you can add formatting or values to the button before assigning it here
table.Rows[0].cells[0] = new DataGridViewButtonCell();
}
I think the best answer if found here:
Hide gridview button. All you need to do is to add a DataGridViewButtonCell where you want buttons, and DataGridViewTextBoxCell where you do not. The column has to be DataGridViewButton type.
See this similar post in SO, probably helps
adding control to gridview
In case Win Form, Check this MSDN post
Column Types in the Windows Forms DataGridView Control
OR this code project post ... though it gives example of adding a image button
DataGridView Image Button Cell
#tmax In that case you can probably put your button creation code in GridView_RowCreated event like below
void GridView_RowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Header)
{
//Button creation code here
}
}
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
Button btn = new Button();
//btn attributes
dataGridView1.Rows[0].Cells[3].Value = new Button();
}
try something like this.
What I endded up doing was stacking a DataGridView on top of another one. I turned off the border, gridlines, and scrollbars. Then create dynamic button columns to match the main datagridview with only one row of buttons. Then I used the ColumnWidthChanged event handler to resize both the DataGridViews together. Anyway's this was my workaround for now.
DataGridViewButtonColumn dataGridViewButtonColumn = new DataGridViewButtonColumn();
dataGridViewButtonColumn.Name = "Select";
dataGridViewButtonColumn.HeaderText = "Select";
dataGridViewButtonColumn.ReadOnly = false;
dataGridView1.Columns.Add(dataGridViewButtonColumn);
After assigning data source to gridviewCTRL. you can add new column with button with below code.
DataGridViewButtonColumn startbtn = new DataGridViewButtonColumn();
startbtn.Name = "Action";
startbtn.Text = "Start";
startbtn.UseColumnTextForButtonValue=true;
int columnIndex = 6;
gridviewCTRL.Columns.Insert(columnIndex, startbtn);
This will add the button to each and every row at define column index.
if you want to render condition the AccessibleObject, then you can do something similar to below.
foreach (DataGridViewRow rowdata in gridviewCTRL.Rows)
{
// this is just an example in my case i am checking a previous column value
if (rowdata.Cells[5].Value=="XYZ")
{
rowdata.Cells[6] = new DataGridViewTextBoxCell();
}
}
This way you can dynamically render/ showing the control in the GridView in Winforms c#.
The above code simple update the cell with new cell. We can't remove button from the cell nor remove whole, so instead we can initial a new cell that will override the button visibility.
I am not sure if this will help but you can also consider using TableLayoutPanel.
Refer: Winforms TableLayoutPanel adding rows programmatically
I am dynamically creating an Item template in a Gridview.
TemplateColumn BtnTmpField = new TemplateColumn();
BtnTmpField.ItemTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.Item, "Edit", "Button");
BtnTmpField.HeaderTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.Header, "Edit", "Command");
BtnTmpField.EditItemTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.EditItem, "Update", "Button"); dgdefault.Columns.Add(BtnTmpField);
public void InstantiateIn(System.Web.UI.Control Container)
{
switch (ItemType)
{
case ListItemType.Header: Literal header_ltrl = new Literal();
header_ltrl.Text = "" + FieldName + "";
Container.Controls.Add(header_ltrl);
break;
case ListItemType.Item:
switch (InfoType)
{
case "Button":
LinkButton edit_button = new LinkButton();
edit_button.ID = "edit_button";
edit_button.Text = "Edit";
edit_button.CommandName = "Edit";
Container.Controls.Add(edit_button);
break;
}
break;
case ListItemType.EditItem:
if (InfoType == "Button")
{
LinkButton update_button = new LinkButton();
update_button.ID = "update_button";
update_button.CommandName = "Update";
update_button.Text = "Update ";
LinkButton cancel_button = new LinkButton();
cancel_button.ID = "cancel_button";
cancel_button.CommandName = "Cancel";
cancel_button.Text = "Cancel";
Container.Controls.Add(update_button);
Container.Controls.Add(cancel_button);
}
break;
}
}
When I select the "Edit" button the "Update" and "Cancel" buttons show up with the selected row editable. The ItemCommand event of the DataGrid fires correctly when "Edit" is clicked. When I click the "Update" or "Cancel" buttons nothing fires. The ItemCommand doesn't fire, and neither does the UpdateCommand or CancelCommand when I explicitly put the onUpdateCommand or onCancelCommand in the ascx page. I can't figure out why nothing is firing when the buttons in the EditItemTemplate is clicked. Also Everything is being loaded on every page_init postback. Any tips would be helpful
I figured it out. I basically created an item template, and added 3 separate buttons without using the edititem. In the data grid itemdatabound function, I just hide and show the buttons that need to be shown.
Are you rebinding the events in the grid's PreRender?
I had the same issue today. I noticed that it was calling the "Header" template for edit items. not sure why, but add the following just before "switch":
System.Diagnostics.Debug.WriteLine(string.Format("Template: {0}",ItemType.ToString()));
if you're testing with a small-ish number of records, you should be able to see that it calls the "header" item type when you attempt to edit the record.
I'd be curious to know if you're experiencing the same thing.
I have a search button on my page that runs a query on a DB, pulls out and displays some entries in a table, and for each entry I create a button. It looks something like this:
List<Friend> friends = SearchFriend(searchStr);
foreach (Friend f in friends)
{
TableCell addCell = new TableCell(), nameCell = new TableCell();
addCell.Text = "";
if (!f.IsMyFriend)
{
LinkButton addFriendBtn = new LinkButton();
addFriendBtn.Text = "Add as Friend";
addFriendBtn.Click += new EventHandler(addFriendBtn_Click);
addFriendBtn.ID = "add_" + f.ID.ToString();
addCell.Controls.Add(addFriendBtn);
}
nameCell.Text = f.Name;
TableRow row = new TableRow();
row.Cells.Add(addCell);
row.Cells.Add(nameCell);
SearchFriendTable.Rows.Add(row);
}
Problem is that the LinkButton event does not fire when it is pressed (changing LinkButton to a simple Button does not fix this either).
This is the html that I get in this portion:
<td><a id="ctl00_contentPH_add_2" href="javascript:__doPostBack('ctl00$contentPH$add_2','')">Add as Friend</a></td>
Also - when I put a breakpoint on Page_Load I do see the __EVENTTARGET with this control's id in it - however the event never starts running.
Any clues?
Thanks.
Adding to Himadri's answer:
Dynamically added controls need to be rewired in page init. Then the event will fire. I had a very similar issue Dynamically loaded Controls in a wizard
Where and when did you created that button?
If you dynamically create Buttons and want to listen to a event you have to create that button in the PageInit event. Always! So do not use if(!IsPostback)
Try with this.
<td><a id="ctl00_contentPH_add_2" href="javascript:__doPostBack('<%=ct100_contentPH_add_2.ClientId %>','')">Add as Friend</a></td>
Add event handler for the link buttons and handle those events.
if (!f.IsMyFriend)
{
LinkButton addFriendBtn = new LinkButton();
addFriendBtn.Text = "Add as Friend";
addFriendBtn.Click += new EventHandler(addFriendBtn_Click);
addFriendBtn.ID = "add_" + f.ID.ToString();
addFriendBtn.Click += new EventHandler(addFriendBtn_Click);
addCell.Controls.Add(addFriendBtn);
}
the event:
protected void addFriendBtn_Click(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
// do your coding
}