how to find a command field control in the gridview.
in a method not in the row data bound.
so far i have used this coding but i cant find the control.
<asp:CommandField ButtonType="Image" ShowEditButton="True
HeaderText="Enter Leave"
EditImageUrl="~/IMAGES/edit-icon.gif">
<ItemStyle HorizontalAlign="Center" />
</asp:CommandField>
source code:
ImageButton edit = (ImageButton)EmployeeDetails.FindControl("Image");
edit.Enabled = false;
You can disable column itself with,
GridView1.AutoGenerateEditButton = false;
from code behind pages.
Or you can use ItemTemplate instead of CommandField,
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="id" CommandName="Edit" Text="Edit" />
</ItemTemplate>
</asp:TemplateField>
And at code behind you can iterate through rows of GridView and disable each LinkButton.
foreach(GridViewRow gvr in GridView1.Rows)
{
LinkButton row = gvr.FindControl("id") as LinkButton;
row.Enabled = false;
}
First Edit :
I tried my second solution and it works. However, make sure your GridView is filled before you use foreach. Otherwise, GridView.Rows.Count would probably be 0.
Second Edit :
This works for CommandField too. Replace 0 with the location of CommandField in your GridView.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Enabled = false;
}
}
You miss to specify the row
Something like :
ImageButton edit = (ImageButton)EmployeeDetails.Rows[0].Cells[0].FindControl("Image");
edit.Enabled = false;
If you want to disable the column that contains the imageButton , you can do :
EmployeeDetails.Columns[0].Visible = false;
Try this:
try to hide controls at DataBound or RowDataBound event of GridView
protected void EmployeeDetails_DataBound(object sender, EventArgs e)
{
ImageButton edit = (ImageButton)EmployeeDetails.Row.Cells[0].FindControl("Image");
edit.Visible = false;
edit.Enabled = false; //OR use this line
}
particular column can be disabled in the following way
EmployeeDetails.Columns[0].Visible = false;
Hope this helps.
I had a similar issue. I simply disabled the view of the Column in BindData() function.
GridView1.Columns[0].Visible = false;
This worked for me, since my first column was Edit column and I have to enable it for specific users only.
Good luck!
Cast it as a DataControlFieldCell and then set Enabled to false.
Where: row.Controls[0] is your CommandField control
foreach (GridViewRow row in ManageDNXGridView.Rows)
{
DataControlFieldCell editable = (DataControlFieldCell)row.Controls[0];
editable.Enabled = false;
}
Related
I want to ask how to get a text or value of a button inside the gridview?
but i want to get the text value from this onrowcommand which use GridViewCommandEventArgs as its parameter.
as if im using onrowdatabound is (GridViewRowEventArgs), which makes it easy for me to get the button.text inside the gridview
string example = ((Button)e.Row.FindControl("btnStop")).Text;
I want to get the button.text to do an if else loop inside the onrowcommand.
Anyone know how?
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" CellPadding="2" CellSpacing="2" HorizontalAlign="Center" PageSize="5" Width="133%" DataKeyNames="SurveyID" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" onrowcommand="stop_survey"
onrowdatabound="filter_select" onselectedindexchanging="selected"
>
code behind
public void filter_select(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{....
((Button)e.Row.FindControl("btnStop")).Text = "Start";
}
}
public void stop_survey(object sender, GridViewCommandEventArgs e)
{
//i want to get the "btnStop" button text which is nested on the gridview.
}
i want to get the btnStop text, as I want to have different sqlstatement depending on its text (eg. Start or Stop)
the problem is i cant do e.Row inside stop_survey.
Please guide me.
Create a object of GridViewRow from refrence of command source row.
GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
But keep in mind that which type of object control is you are using to call event in above code is LinkButton. But if You Calling Rowcommand event from Simple Button then You need to Write this:
GridViewRow row = (GridViewRow)((Button)e.CommandSource).NamingContainer;
After Creating Row Object You can simply find any control from Gridview using rowindex.
Label LabelEmail = (Label)GridView1.Rows[row.RowIndex].FindControl("LabelEmail");
Finally You Can Access that Properties of that Control.
LabelResult.Text = LabelEmail.Text;
Same as Above You can also find Datakeys of gridview using GridViewRow rowindex.
int code = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0].ToString());
<asp:TemplateField HeaderText="Select One">
<ItemTemplate>
<asp:RadioButton ID="RadioButton1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow di in GridView1.Rows)
{
RadioButton rad = (RadioButton)di.FindControl("RadioButton1");
if (rad.Checked&&rad!=null)
{
s = di.Cells[1].Text;
}
}
Response.Redirect("applicants.aspx?form=" +s);
}
I'm selecting the rows that are selected with this but I have a problem here I want user to be able to select only one radiobutton but its allowing all the radiobuttons to be selected at once.Can you help me in removing this problem please.
please.
Maybe I'm too late here on the party but this will do the trick,
check out here......
This might be useful for someone watching this answer in the future.
In the ASP page you need to set the GroupName property to be the same for all the radio buttons, e.g.:
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="RadioGroup" />
well for that you can use follwing code
first of all you should define the groupName.The follwing code will work
<asp:RadioButton ID="RadioButton1" OnCheckedChanged="rbSelector_CheckedChanged" AutoPostBack="true" GroupName="Apply" runat="server"></asp:RadioButton>
C#
protected void rbSelector_CheckedChanged(object sender, System.EventArgs e)
{
foreach (GridViewRow oldrow in GridView2.Rows)
{
((RadioButton)oldrow.FindControl("RadioButton1")).Checked = false;
}
//Set the new selected row
RadioButton rb = (RadioButton)sender;
GridViewRow row = (GridViewRow)rb.NamingContainer;
((RadioButton)row.FindControl("RadioButton1")).Checked = true;
}
You can try this link to select single radiobutton in grid : http://www.c-sharpcorner.com/uploadfile/krishnasarala/select-single-radio-button-in-gridview-in-Asp-Net/
Using the GroupName property by itself won't work, each radio button will still get a unique name attribute since they're in different rows of the grid.
One option is to emit the radio button markup manually using a Literal control (example). This will make it easy to group the radio buttons on the client-side, but requires a bit more work to determine which button was selected on postback.
When I needed this behavior, I found it easier to keep the radio buttons as server-side controls, and just enforce the button group w/ jQuery. Put your RadioButton in a TemplateField as you've shown, then add this code to uncheck all the other buttons when one is checked:
$(document).ready(function () {
// could also pass in a unique ID selector
createManualRadioButtonGroupForGridView(".myGridViewClass");
});
function createManualRadioButtonGroupForGridView(gridViewSelector) {
$(gridViewSelector + " input[type=radio]").change(function () {
var checkedRadioButton = this;
$(gridViewSelector + " input[type=radio]").each(function (e) {
if (this !== checkedRadioButton) {
$(this).prop("checked", false);
}
});
});
}
Is it possible to have a Checkbox that only shows up when Editing the last row of a GridView?
I have tried something like this in the EditItemTemplate:
<asp:CheckBox ID="chkNextDay" runat="server"
ToolTip="Is it a next-day departure?"
Enabled="true"
Checked='<%# DateTime.Parse(Eval("OutHour","{0:d}")).Date >
DateTime.Parse(Eval("InHour","{0:d}")).Date %>'/>
Then on code-behind I tried hiding it for rows other than the last one like this:
protected void grvOutHour_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView grvOutHour = (GridView)this.grvReport.Rows[grvReport.EditIndex].FindControl("grvOutHour");
TextBox txtBox = (TextBox)grvOutHour.Rows[e.NewEditIndex].FindControl("txtEditOutHour");
CheckBox nextDay = (CheckBox)grvOutHour.Rows[e.NewEditIndex].FindControl("chkNextDay");
if (grvOutHour.Rows.Count-1 != e.NewEditIndex)
nextDay.Visible = false;
}
This ALMOST worked, but the checkbox kept showing for all fields, I think because the RowDataBound is called AFTER RowEditing again so it renders the whole thing again :(
Any suggestions?
Thanks,
EtonB.
Use RowDataBound instead...
protected void grvOutHour_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
GridView grid = (GridView)sender;
CheckBox nextDay = (CheckBox)e.Row.FindControl("chkNextDay");
nextDay.Visible = (e.Row.RowIndex == (grid.Rows.Count - 1));
}
}
You will need to handle hiding the checkbox in the RowDataBound event.
You'll need to determine what the last row is, and set the checkboxes visible property to true when that condition is true, obviously.
I guess it's more of a hack than an elegant solution, but I would probably just hide the other checkboxes via JavaScript if the condition is true.
In a DataGrid, when text in a textbox changes I want to add the value of another field in that row to an array.
public void txtTitle_TextChanged(object sender, EventArgs e)
{
TextBox titleBox = (TextBox)sender;
DataGridItem myItem = (DataGridItem)titleBox.Parent.Parent;
string test = DataBinder.Eval(myItem.DataItem, "prod_id").ToString();
}
However myItem.DataItem evaluates as null. I was expecting it to evaluate as DataRowView?
You can get the TextChanged event to fire if you do the following:
<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="False"
onitemdatabound="DataGrid1_ItemDataBound">
<Columns>
<asp:TemplateColumn HeaderText="Test">
<ItemTemplate>
<asp:TextBox OnTextChanged="txtBox_TextChanged" ID="TextBox1" runat="server" AutoPostBack="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="Name" HeaderText="Test 1"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
You will notice that i have the following properties set:
AutoPostBack="True"
I have also manually added the OnTextChanged="txtBox_TextChanged" to the text box as well.
In my code behind i have:
protected void txtBox_TextChanged(object sender, EventArgs e)
{
TextBox txtBox = (TextBox)sender;
Label1.Text = txtBox.Text;
}
The only way the event will fire is when you lose focus on the text box after typing.
Key points to consider:
This will cause a post back, so Ajax might be a good way to keep the user experience nice.
You will need to make sure you wrap your DataBind() in a if (!IsPostBack)
Hope this helps!
Effectively, I solved this by adding an autonumber column to the table, and using the value of this to determine the row's positino in the table, then using the value of this to affect the appropriate row in the datagrid.
I'm now merely changing the color of the row rather than adding values in that row to an array, as stated in the original question.
public void txtPrice_TextChanged(object sender, EventArgs e)
{
TextBox txtPrice = (TextBox)sender;
DataGridItem myItem = (DataGridItem)txtPrice.Parent.Parent;
markRows(myItem, true);
}
public void markRows(DataGridItem myItem, bool toSave)
{
// Prepeare to save this record?
CheckBox thisSave = (CheckBox)myItem.FindControl("chkSave");
thisSave.Checked = toSave;
// Establish the row's position in the table
Label sNo = (Label)myItem.FindControl("SNo");
int rowNum = Convert.ToInt32(sNo.Text) - 1;
CheckBox rowSave = (CheckBox)grid.Items[rowNum].FindControl("chkSave");
// Update background color on the row to remove/add highlight
if (rowSave.Checked == true)
grid.Items[rowNum].BackColor = System.Drawing.Color.GreenYellow;
else
{
Color bgBlue = Color.FromArgb(212, 231, 247);
grid.Items[rowNum].BackColor = bgBlue;
// some code here to refresh data from table?
}
}
I am creating a gridView that allows adding new rows by adding the controls necessary for the insert into the FooterTemplate, but when the ObjectDataSource has no records, I add a dummy row as the FooterTemplate is only displayed when there is data.
How can I hide this dummy row? I have tried setting e.row.visible = false on RowDataBound but the row is still visible.
You could handle the gridview's databound event and hide the dummy row. (Don't forget to assign the event property in the aspx code):
protected void GridView1_DataBound(object sender, EventArgs e)
{
if (GridView1.Rows.Count == 1)
GridView1.Rows[0].Visible = false;
}
Please try the following
protected void GridView1_DataBound(object sender, EventArgs e)
{
GridView1.Rows[0].Visible = false;
}
I think this is what you need:
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false" ShowFooter="true" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:TemplateField HeaderText="headertext">
<ItemTemplate>
itemtext
</ItemTemplate>
<FooterTemplate>
insert controls
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and the codebehind:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["style"] = "display:none";
}
}
But I do not understand why you are adding your "insert controls" to the footer instead of placing them below the grid.
Maybe try:
e.Row.Height = Unit.Pixel(0);
This isnt the right answer but it might work in the meantime until you get the right answer.
Maybe use CSS to set display none?!
This is the incorrect usage of the GridView control. The GridView control has a special InsertRow which is where your controls should go.
GridView has a special property to access Footer Row, named "FooterRow"
Then, you cold try yourGrid.FooterRow.Visible = false;
I did this on a previous job, but since you can add rows, I always had it visible in the footer row. To make it so that the grid shows up, I bound an empty row of the type that is normally bound
dim row as Datarow = table.NewRow()
table.AddRow(row)
gridView.DataSource = table
gridView.Databind()
then it has all the columns and then you need. You can access the footer by pulling this:
'this will get the footer no matter how many rows there are in the grid.
Dim footer as Control = gridView.Controls(0).Controls(gridView.Controls(0).Controls.Count -1)
then to access any of the controls in the footer you would go and do a:
Dim cntl as Control = footer.FindControl(<Insert Control Name Here>)
I'd assume you'd be able to do a:
footer.Visible = false
to make the footer row invisible.
I hope this helps!
Edit I just figured out what you said. I basically delete the row when I add a new one, but to do this you need to check to see if there are any other rows, and if there are, check to see if there are values in it.
To delete the dummy row do something like this:
If mTable.Rows.Count = 1 AndAlso mTable.Rows(0)(<first column to check for null value>) Is DBNull.Value AndAlso mTable.Rows(0)(<second column>) Is DBNull.Value AndAlso mTable.Rows(0)(<thrid column>) Is DBNull.Value Then
mTable.Rows.Remove(mTable.Rows(0))
End If
mTable.Rows.Add(row)
gridView.Datasource = mTable
gridView.Databind()
Why are you not using the EmptyDataTemplate? It seems to work great even though I have only been using it for a couple days...
You should use DataKeyNames in your GridView:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="FooID">
And then retrieve it on your code:
GridView1.DataKeys[0].Value.ToString()
Where "0" is the number of the row you want to get the "FooID"
To make it visible, just use:
Gridview.Rows.Item(i).Attributes.Add("style", "display:block")
And to make it invisible
Gridview.Rows.Item(i).Attributes.Add("style", "display:none")
If you do not want to display data when the column/row is null:
if (!String.IsNullOrEmpty(item.DataName))
{
e.Row.Visible = false;
}
It can easily be done by SQL
USE YourdatabaseName select * from TableName where Column_Name <> ''