How to set disable or readonly in a datagrid view - asp.net

I have the following datagrid view that is data bound with some data at the DB
I need to load the information in the data grid and make all the textbox in some columns(in the example only comes on but there are many) to be readonly or disable.
<asp:DataGrid ID="grdRequestTypeItem" TabIndex="1" runat="server" CssClass="Grid" AutoGenerateColumns="False"
AllowSorting="True" Visible="true">
<SelectedItemStyle CssClass="GridSelectedItem"></SelectedItemStyle>
<AlternatingItemStyle CssClass="GridAlternatingItem"></AlternatingItemStyle>
<ItemStyle CssClass="GridItem"></ItemStyle>
<HeaderStyle CssClass="GridHeader"></HeaderStyle>
<Columns>
<asp:TemplateColumn HeaderText="Lot Number">
<ItemTemplate >
<asp:TextBox ID="txtLot" runat="server" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.Lot") %>' />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
How can I disable that column in the code behind ??
Neither of the following are working
grdRequestTypeItem.Columns[1].IsReadOnly = true;
((BoundField)grdRequestTypeItem.Columns[0]).ReadOnly = true;
((TemplateField)grdRequestTypeItem.Columns[0]).EditItemTemplate = null;

Even if your DataGrid is not in EditMode it displays the TextBox inside the ItemTemplate. Otherwise you use an EditItemTemplate. That's why neither of your solutions work. You have several options:
Put a <asp:Literal> Control into your ItemTemplate
Bind the ReadOnly property of the TextBox to a bool value of your viewModel
from code behind, you have to address the correct control
you could use something like this to reference the textbox within the item template
foreach (GridViewRow row in grdRequestTypeItem.Rows)
{
var txtLot = row.FindControl("txtLot") as TextBox;
txtLog.IsReadOnly = true;
}
You could also use the DataBinding Event on the row instead of looping through the rows like in the answer of #Stealth22

Try this:
<asp:DataGrid ID="grdRequestTypeItem" TabIndex="1" runat="server" CssClass="Grid" AutoGenerateColumns="False" AllowSorting="True" Visible="true"
OnItemDataBound="grdRequestTypeItem_ItemBound">
And then in your code-behind...
protected void grdRequestTypeItem_ItemBound(Object sender, DataGridItemEventArgs e)
{
if((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
TextBox txtLot = e.Item.FindControl("txtLot");
if (txtLot != null)
{
txtLot.ReadOnly = true;
}
}
}
Someone can correct me if I am wrong anywhere, as I work more with GridViews than DataGrids, but as far as I know, the principle is the same.

Related

Unable to get selected item of dx:ASPxListBox on ASPxGridView_Updating event of devexpress control

I have used dx:ASPxGridView where I have one dx:GridViewDataTextColumn with EditItemTemplate which contain dx:ASPxListBox. When I click on update command I am not able to get selected items of dx:ASPxListBox under ASPxGridView_Updating.
<dx:ASPxGridView
ID="ASPxGridView"
runat="server"
AutoGenerateColumns="False"
DataSourceID="TradersDS"
KeyFieldName="TraderId">
<SettingsEditing Mode="PopupEditForm" PopupEditFormWidth="600px" />
<ClientSideEvents RowDblClick="function(s, e)
{
s.StartEditRow(e.visibleIndex);
}"
EndCallback="PrepareGridViewForNewDesing" Init="PrepareGridViewForNewDesing" />
<Columns>
....
<dx:GridViewDataTextColumn FieldName="CounterParty" VisibleIndex="3">
<EditItemTemplate>
<dx:ASPxListBox ID="lstCounterParty" runat="server" SelectionMode="CheckColumn" EnableSelectAll="true"
Width="285"
Height="300"
DataSourceID="CounterPartiesDS"
ValueField="ID"
ValueType="System.String"
TextField="Name">
<%-- <ClientSideEvents SelectedIndexChanged="function(s, e) {lbModels.PerformCallback('1');}" />--%>
</dx:ASPxListBox>
</EditItemTemplate>
</dx:GridViewDataTextColumn>
...
</Columns>
</dx:ASPxGridView>
C# Code..
protected override void ASPxGridView_Updating(object sender, ASPxDataUpdatingEventArgs e)
{
var gridView = sender as ASPxGridView;
GridViewDataColumn list = gridView.Columns["CounterParty"] as GridViewDataColumn;
var counterPartyListBox = (ASPxListBox)gridView.FindEditRowCellTemplateControl(list, "lstCounterParty");
string selectedItemsAsString = string.Empty;
foreach (ListEditItem item in counterPartyListBox.SelectedItems)
selectedItemsAsString += item.Value + ";";
base.ASPxGridView_Updating(sender, e);
}
Here I always get count 0 of SelectedItems. On addition to this My devExpress control version are 9.3.3
What is wrong with this code any help , guidance really appreciated.
Make sure that you set the ASPxListBox.ValueType property to the corresponding .NET type that matches the type of the "ValueField" column.
May be, according to the (ValueField="ID"), the (ASPxListBox.ValueType) should be numeric? (System.Int32, etc.)

Row background color in gridview?

In asp.net application, I am using grid-view control in that I am binding the data to the label which is in grid-view.
If data is empty then the color of the row should be in red
If not I mean if data is there to bind then the row in green.
This is my code:
<asp:TemplateField HeaderText ="Holiday Region">
<ItemTemplate >
<asp:Label ID ="lblholdareg" runat ="server" Text ='<%# Eval("Holidaregion") %>' >
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
You need to handle the RowDataBound event, get into the e.Row item, and assign either a CSS class or directly set the background color. I prefer setting a CSS class so you can change the rendering of it without a recompile later.
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Holiday Region">
<ItemTemplate>
<asp:Label ID="lblholdareg" runat="server" Text='<%# Eval("Holidaregion") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code-behind, I had to assume you were using a DataTable as your data source, update the code to fit your data structure:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
System.Data.DataRow row = (System.Data.DataRow)e.Row.DataItem;
if (row["Holidaregion"] == null || row["Holidaregion"].ToString().Trim().Length == 0)
{
e.Row.CssClass = "row-empty";
}
else
{
e.Row.CssClass = "row-full";
}
}
You can do it on rowdatabound function of gridview as follows
protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//change it according your cell number or find element
if(e.Row.Cells[0].Text != "")
e.Row.BackColor = Color.Green;
else
e.Row.BackColor = Color.Red;
}
}
if(e.Row.RowType == DataControlRowType.DataRow)
{
Control l = e.Row.FindControl("Label1");
((Label)l).BackColor = System.Drawing.Color.Red;
}
Try something like this
<asp:TemplateField HeaderText ="Holiday Region">
<ItemTemplate >
<asp:Label ID ="lblholdareg" runat ="server"
CSSClass='<%# (String.IsNullOrEmply(Eval("Holidaregion")))?"red:green" %>'
Text ='<%# Eval("Holidaregion") %>' >
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Edit:
Instead of fighting with grid view inline and code behind stuffs, just use a jQuery and achieve the same in client side
try it this code it is every row in color change with the category wise or filters wise
http://devloper4u.blogspot.in/2013/10/how-to-set-color-in-every-row-on.html

Lost Focus Events for a Control Within GridView

I have multiple textboxes and dropdown lists within my GridView. For one particular textbox I need trigger a server event which gets data from the database and fills it in other columns of the Grid. Is there a simple way to do it or a slightly complicated way as detailed here
I have no problems implementing the above method or thinking of a work around but then thought that there is Cell Lost Focus in a grid control surprises me a little. Am I missing something ? Any help on this would appreciated.
You can set AutoPostBack to true and handle it's TextChanged event.
<asp:GridView ID="GridView1" runat="server" EmptyDataText="It's Empty.">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="txtName"
runat="server"
Text='<%#Eval("Name") %>'
AutoPostBack="true"
OnTextChanged="NameChanged" >
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</GridView>
in codebehind:
protected void NameChanged(Object sender, EventArgs e)
{
var txtName = (TextBox) sender;
var row = (GridViewRow) txtName.NamingContainer;
// you could find other controls in this GridViewRow via
// row.FindControl("ControlID") in case of a TemplateField or
// row.Cells[0].Text (0 = index of column) in case of a BoundField
}

Unable to access the checkbox for Serverside coding

Below is my gridview ,
<asp:GridView ID="gridview1" AutoGenerateColumns="False" runat="server"
EnableModelValidation="True" >
<Columns>
<asp:CommandField ButtonType="Link" HeaderText="Delete" InsertImageUrl="~/_layouts/images/TBS.WebParts/Button-Delete-icon.png" ShowDeleteButton="true"/>
<asp:BoundField HeaderText ="Size" DataField="FileSize" />
<asp:BoundField HeaderText ="File" DataField="Size" />
<asp:TemplateField HeaderText="SupportIncluded">
<ItemTemplate>
<asp:CheckBox ID="Checkbox1" runat="server" Checked="false" />
</ItemTemplate>
Now on server side i want to check if the checkbox is checked or not on Submit button click event.
private void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValidPost())
{
bool flag = false;
for( int i=0; i < gridview1.Rows.Count ; i++)
{
if(dgdUpload.Rows[i].FindControl("Checkbox1"),CheckBox).Checked) erorr here...I also tried ....if(Checkbox1.checked)...but unable to access Checkbox1..it says it does not exist in the current context....
flag = true;
}
if(flag)
{
}
}
}
You need to access not only the row but also the template field control. Another option is to develop your own recursive version of FindControl that does a search on the whole tree and not just on one level.
Something like:
dgdUpload.Rows[i].Controls[5].FindControl("Checkbox1")
if I counted the columns in your gridview correctly 5 should be the index of the template field.

DataBound DropDownList in DataGrid - order of binding

I have a DataGrid that looks like this (slightly simplified here):
<asp:DataGrid ID="grdQuotas" runat="server" AutoGenerateColumns="False">
<HeaderStyle CssClass="quotas-header" />
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
Max order level</HeaderTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlMaxOrderLevel" runat="server" DataSourceID="xdsOrderLevel"
DataTextField="Text" DataValueField="Value" SelectedValue='<%# Bind("MaxOrderLevel") %>'>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:XmlDataSource ID="xdsOrderLevel" runat="server" DataFile="~/App_Data/OrderLevels.xml">
</asp:XmlDataSource>
In my Page_Load event handler I am creating a DataTable containing default values and DataBinding it to the DataGrid.
The problem is that this is taking place before the DropDownList ddlMaxOrderLevel has been bound to its DataSource, so I get a runtime error telling me that the SelectedValue cannot be set.
If ddlMaxOrderLevel was not in a DataGrid I could just call DataBind() on it. However I cannot do that in this scenario - since it is in an ItemTemplate.
Can anyone suggest a workaround or alternate approach?
You could do the Databinding of the DropDownlist in the Databound event of the DataGrid.
Edit:
I will give you an example that i have tested:
protected void dg_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)
{
DropDownList dl = (DropDownList)((DataGridItem)e.Item).FindControl("ddlMaxOrderLevel");
dl.DataSource = levels;
dl.DataBind();
dl.SelectedValue = ((DataRowView)e.Item.DataItem)["number"].ToString();
}
}
Create another DataSource and bind it to the DataGrid. Where the SelectMethod would return the default values in a simple object.
Then all the binding should happily work together.

Resources