How to limit textbox template field text length in gridview? - c#

<asp:GridView ID="CommentGrid" GridLines="None" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="No." DataField="Num" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField HeaderText="Subject Name" DataField="SubjectName">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:TextBox ID="CommentBox" runat="server" TextMode="MultiLine" CssClass="commentTbx" MaxLength="2"></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>
The above Maxlength="2" doesnt work!! I even tried other method like databound, and foreach loop to code it but it still fails.

User RegularExpressionValidator. The following accepts minimum characters 0 and maximum 2 characters.
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="CommentBox" ErrorMessage="Out of Range Max 2 Chars"
ValidationExpression=".{0,2}"></asp:RegularExpressionValidator>
MaxLength does not work on MultiLine mode.

Yes, it is because of TextMode="MultiLine" . You need some javascript to check total chars and impose limit.

Have you tried <EditItemTeplate> instead of <ItemTemplate>?

Related

How to fix the width for each column in GridView?

How can I fix the width for each column in GridView. My GridView keeps extend along with data in the cell. I need it to skip to new line when it reach the right side of the cell. This is my code in .aspx file:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="Emp_ID" DataSourceID="LinqDataSource1"
AllowPaging="True" AllowSorting="True" Width="900px" HorizontalAlign="Center" >
<Columns>
<asp:BoundField DataField="Emp_ID" HeaderText="ID"
InsertVisible="False" ReadOnly="True" SortExpression="Emp_ID"/>
<asp:BoundField DataField="Emp_Username"
HeaderText="Username" SortExpression="Emp_Username" />
<asp:BoundField DataField="Emp_Password"
HeaderText="Password" SortExpression="Emp_Password" />
<asp:BoundField DataField="Emp_Name"
HeaderText="ชื่อพนักงาน" SortExpression="Emp_Name" />
<asp:BoundField DataField="Emp_Address"
HeaderText="ที่อยู่" SortExpression="Emp_Address" />
<asp:BoundField DataField="Emp_Tel"
HeaderText="เบอร์โทรศัพท์" SortExpression="Emp_Tel" />
<asp:TemplateField HeaderText="รูปพนักงาน" SortExpression="Emp_Picture">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Emp_Picture") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image2" runat="server" Height="70px"
ImageUrl='<%# Eval("Emp_Picture", "{0}") %>' Width="50px" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Status" HeaderText="สถานะ"
SortExpression="Status" />
<asp:HyperLinkField DataNavigateUrlFields="Emp_ID"
DataNavigateUrlFormatString="AdminUpdate.aspx?Emp_ID={0}" Text="Edit" />
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="ChkSelectAll" runat="server"
AutoPostBack="True" oncheckedchanged="ChkSelectAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="Chk" runat="server" AutoPostBack="True" oncheckedchanged="Chk_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here's my design view:
As you can see, the first 4 columns has no problem with that until column 5. It keeps extend cause all GridView extend out of the page
Set itemstyle width of every column.For example.
<asp:BoundField DataField="Emp_Address"
HeaderText="ที่อยู่" SortExpression="Emp_Address">
<ItemStyle Width="200px" HorizontalAlign="Left" />
</asp:BoundField>
Wrapping is done based on words so that any single word is not broken in two lines.
So won't work for you if your data has long string without space.
The problem is that you can't insert spaces on your own because that may change the meaning of data.
While showing in grid we show only that long string which can be accommodated in column and then add "..." (only if string is more than what is showing) and then add a tooltip to show the full string.
That way the grid formatting is not compromised and if user wants he can hover his mouse and see the whole string.
hope this helps Example
Try setting the property RowStyle-Wrap of the GridView to True.
You can use ItemStyle-Width to fix the column width ,but in case you enter characters which can not be enclosed in given width (As seen in your image) ,column will expand as per the inputs so you can use RowStyle-Wrap property of gridview
<asp:GridView ID="grdVwtrial" runat="server" RowStyle-Wrap="true">
RowStyle-Wrap==true should work I guess. For more clarifications refer this:
http://forums.asp.net/t/1263769.aspx

gridview CommandField Update & cancel image coming Up down on IE

i am using Gridview.
my code is:
<asp:GridView ID="gvReceivers" runat="server" AutoGenerateColumns="False"
BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px"
CellPadding="2" ForeColor="Black" GridLines="None"
OnRowEditing="RowEditing" Font-Size="Medium"
OnSelectedIndexChanging="gvReceivers_SelectedIndexChanging"
onrowcancelingedit="gvReceivers_RowCancelingEdit"
onrowdeleting="gvReceivers_RowDeleting"
onrowupdating="gvReceivers_RowUpdating">
<FooterStyle BackColor="Tan" />
<Columns>
<asp:CommandField ShowEditButton="True" ButtonType="Image"
CancelImageUrl="~/Images/Cancel.png" UpdateImageUrl="~/Images/save.png"
EditImageUrl="~/images/Edit.png" ItemStyle-Width="25px"
UpdateText="Update" CancelText="Cancel" />
<asp:CommandField ShowDeleteButton="true"
DeleteImageUrl="~/Images/delete.png" ButtonType="Image"
ItemStyle-Width="25px" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton runat="server" ID="imgSelect"
CommandName="Select" AlternateText="Select"
ImageUrl="~/Images/allowed.png" />
</ItemTemplate>
</asp:TemplateField>
now, i click on edit image. update & cancel images & Event are coming.but issue is on IE Update & Cancel image coming Up & Down. it's working fine on Mozila & chrome.check below image.
It's simple just add ItemStyle-Wrap="false" in your column.
It seems you have not given any width for ItemTemplate, you can take two separate ItemTemplate or you can also work with single.
<asp:TemplateField HeaderText="ColumnHeader">
<EditItemTemplate>
//You controls
</EditItemTemplate>
<ItemStyle Width="30%" />
*Edit *
You can follow this link and update code accordingly. If get stuck any where then you can ask me. Here we can guide you but the main task you have to do your self.
As Dorel Domocos suggested, I managed to solve the line break using the ItemStyle Wrap in the CommandField.
For example:
<asp:CommandField ButtonType="Image" ShowEditButton="True" EditImageUrl="~/images/edit.png" CancelImageUrl="~/images/cancel.png" UpdateImageUrl="~/images/update.png" ItemStyle-Wrap="false" >
<ItemStyle Wrap="False" Width="48px"></ItemStyle>
</asp:CommandField>
It can be either on the CommandField with the attribute ItemStyle-Wrap="false", or with its ItemStyle element with Wrap="False" attribute.
The generated result has the white-space:nowrap; CSS style, having the following when being in Edit mode:
<td style="width:48px;white-space:nowrap;">
<input type="image" name="GridView1$ctl02$ctl00" src="images/update.png" alt="Update">
<input type="image" src="images/cancel.png" alt="Cancel" onclick="javascript:__doPostBack('GridView1','Cancel$0');return false;">
</td>
Hope it helps.
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton runat="server" ID="imgSelect"
CommandName="Select" AlternateText="Select"
ImageUrl="~/Images/allowed.png" />
</ItemTemplate>
<ItemStyle Width="30%" />
</asp:TemplateField>

Difference between <Fields> and <Columns> in <asp:GridView>

Well it so happens that I am kind of a novice to asp.net and trying to create a Grid whose source is declared programmatically.
In the process, I came across 2 tags Fields and Columns. Can anyone please tell me how they are different?
EDIT: I went through some sample MSDN examples, and for all I can tell it seems to me they can be used interchangeably(though I have a feeling thats not true!).
Check this out:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="ObjectDataSource1">
<Columns>
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="Title" HeaderText="Title"
SortExpression="Title" />
<asp:BoundField DataField="HireDate" HeaderText="HireDate"
SortExpression="HireDate" />
</Columns>
</asp:GridView>
And then there is:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateRows="False" DataKeyNames="ProductID"
DataSourceID="ObjectDataSource1" EnableViewState="False">
<Fields>
<asp:BoundField DataField="ProductName" HeaderText="Product"
SortExpression="ProductName" />
<asp:BoundField DataField="CategoryName"
HeaderText="Category"
ReadOnly="True" SortExpression="CategoryName" />
<asp:BoundField DataField="SupplierName"
HeaderText="Supplier"
ReadOnly="True" SortExpression="SupplierName" />
<asp:BoundField DataField="QuantityPerUnit"
HeaderText="Qty/Unit" SortExpression="QuantityPerUnit" />
<asp:BoundField DataField="UnitPrice"
DataFormatString="{0:c}"
HeaderText="Price"
HtmlEncode="False" SortExpression="UnitPrice" />
</Fields>
</asp:GridView>
Seem similar or is it just me??!
Thanks for helping.
Columns is just the surrounding tag for the fields which are
TemplateFields with any controls you want or
BoundFields which are created automatically
So Columns enclose the list of fields in the GridView.
<Columns>
<asp:Boundfield datafield="StudentID"
readonly="true"
headertext="Student ID"/>
<asp:TemplateField HeaderText="Student" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:label runat="server" Font-Bold="true" ID="LblStudent" Text='<%# Bind("Student") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Inner Grid">
<ItemTemplate>
<asp:GridView ID="Grid2" AutoGenerateColumns="false" runat="server" GridLines="None" Width="300">
<RowStyle CssClass="GridViewRowStyle" />
<AlternatingRowStyle CssClass="GridViewAlternatingRowStyle" />
<HeaderStyle CssClass="GridViewHeaderStyle" />
<SelectedRowStyle BackColor="Aqua" />
<Columns>
<asp:TemplateField HeaderText="Student" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:label runat="server" Font-Bold="true" ID="LblStudent" Text='<%# Bind("Student") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
As you can see, a TemplateField could also contain another nested GridView.
Am I blind or wat!
After I posted this question I went back to my drawingboard and as it turns out, there is no Fields tag in asp:GridView, right?!
Please do let me know if this is true people(and prove me silly!)
Putting aside this particular control for a moment, it might be helpful to look at this from a general computer science point of view.
In classic programming (ANY LANGUAGE), a FIELD would be the INTERSECTION of a row and a column -- a discrete piece of data. For example, if a table has 20 rows of data containing first and last names, if you went to the 19th row and looked in the "first name" column, you've got a FIELD. Perhaps it contains the discrete data "JOHN".
COLUMNS then would be collections of like data -- in this example, you have the two columns "first name" and "last name". Columns would have attributes such as a data type, maximum length, constraints (are nulls OK?, etc.) and so forth.
Some may quibble with my definitions and say that individual cells in a COLUMN would be called a FIELD. It's not uncommon to hear that. I would reply that for a table with a single column, it'd be especially true :-) But the takeaway point is this: COLUMNS are generally containers for smaller, more discrete items such as FIELDS. FIELDS typically refer to a single piece of data, such as you'd find at the intersection of a row and column in a database table.

Gridview OnRowCreated event gets triggered multiple times - dropdownlist gets populated twice

Attaching the code below - its a simple code that just initializes the dropdown (calling ddl.Clear()) and adds an item with text "select" which has value "-1".
Filldropdowns(ddl) are methods that get specific data and populate it into the dropdown method. The methods individually work fine outside the gridview on normal dropdownlists.
What happens is this eventhandler gets called more than once for each gridview row. As an end result, the dropdowns contain double the values they are supposed to contain (the complete set of values just get repeated).
Anyone knows why this is happening? Turning off appenddatabounditems is not an option because i need the items to be appended below the "select".
Strange thing is, when I debug, even on the second time call for the same row, it shows that the dropdownvalues contain zero items and then contains the required number of items. But by the time I reach grdAccountsMapping_DataBound() handler, it shows twice the number of items.
public void grdAccountsMapping_RowCreated(object sender, GridViewRowEventArgs e)
{
GridViewRow row = e.Row;
if (row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlGrdFeeFormat = (DropDownList)row.FindControl("ddlFeeFormat");
DropDownList ddlGrdTransactionMode = (DropDownList)row.FindControl("ddlTransactionMode");
DropDownList ddlGrdFeeParticular = (DropDownList)row.FindControl("ddlFeeParticular");
DropDownList ddlGrdCompany = (DropDownList)row.FindControl("ddlCompany");
DropDownList ddlGrdAccounts = (DropDownList)row.FindControl("ddlAccounts");
DropDownList ddlGrdFeeBook = (DropDownList)row.FindControl("ddlFeeBook");
InitializeDropdown(ddlGrdFeeBook);
InitializeDropdown(ddlGrdFeeFormat);
InitializeDropdown(ddlGrdTransactionMode);
InitializeDropdown(ddlGrdFeeParticular);
InitializeDropdown(ddlGrdCompany);
getDDLValues.FillFeeBooks(ddlGrdFeeBook);
getDDLValues.FillFeeFormats(ddlGrdFeeFormat);
getDDLValues.FillPaymentModes(ddlGrdTransactionMode);
getDDLValues.FillFeeParticulars(ddlGrdFeeParticular);
getDDLValues.FillAccountingCompanies(ddlGrdCompany);
}
}
The aspx page grid definition looks like this
<asp:GridView CssClass="Grid" ID="grdAccountsMapping" runat="server" Width="98%"
EmptyDataText="No records found in this section" EmptyDataRowStyle-Height="40px"
AutoGenerateColumns="False" AccessKey="2" DataKeyNames="FAM_MAP_ID" OnRowCommand="grdAccountsMapping_RowCommand"
OnRowCreated="grdAccountsMapping_RowCreated" OnDataBound="grdAccountsMapping_DataBound"
Visible="false">
<AlternatingRowStyle CssClass="alternateGridItem" HorizontalAlign="Left" />
<RowStyle CssClass="gridItem" HorizontalAlign="Left" />
<EmptyDataRowStyle CssClass="gridItem" HorizontalAlign="Center" Font-Bold="True"
ForeColor="Red" Height="40px" VerticalAlign="Middle" />
<HeaderStyle CssClass="tabledarklabel" />
<FooterStyle CssClass="Grid_Footer" />
<Columns>
<asp:TemplateField HeaderText="Fee Book">
<ItemTemplate>
<asp:DropDownList ID="ddlGrdFeeBook" CssClass="dropdownwidth3" runat="server" AppendDataBoundItems="True">
</asp:DropDownList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle Width="5%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Fee Format">
<ItemTemplate>
<asp:DropDownList ID="ddlGrdFeeFormat" CssClass="dropdownwidth3" runat="server" AppendDataBoundItems="True">
</asp:DropDownList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle Width="5%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Transaction Mode">
<ItemTemplate>
<asp:DropDownList ID="ddlGrdTransactionMode" CssClass="dropdownwidth3" runat="server"
AppendDataBoundItems="True" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Fee Particulars">
<ItemTemplate>
<asp:DropDownList ID="ddlGrdFeeParticular" CssClass="dropdownwidth3" runat="server"
AppendDataBoundItems="True">
</asp:DropDownList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle Width="5%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Company">
<ItemTemplate>
<asp:DropDownList ID="ddlGrdCompany" CssClass="dropdownwidth3" runat="server" AppendDataBoundItems="True">
</asp:DropDownList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle Width="5%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Account">
<ItemTemplate>
<asp:DropDownList ID="ddlGrdAccounts" CssClass="dropdownwidth3" runat="server" AppendDataBoundItems="True">
</asp:DropDownList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle Width="5%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:CheckBox ID="chkActive" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle Width="5%" />
</asp:TemplateField>
</Columns>
<PagerSettings Visible="False" />
<PagerStyle BorderStyle="None" />
</asp:GridView>
The other methods used just retrieve a dataset for the data needed, assign it to the datasourceo of the dropdown and then bind it to the dropdownlist control. Those methods work fine on dropdowns outside the grid, and I have unit tested them - so I am sure the problem is not there.
How are you binding the grid? Are you calling DataBind() and/or Rebind() multiple times by accident?
We just deleted the file and created it again and it seemed to work. I din't have much time to dig into the details since we were on a deadline, but that wierd issue has not happened again!

Anyone have experience with Telerik's RadGrid Paging?

I am having an issue with the paging system on Telerik's RadGrid (AJAX). First take a look at this screenshot:
As you can see, the First/Last Prev/Next buttons are there, but there is no markings on them. Also, the dropdown (thats where those values are coming from) and whatever that 'select' is are really messed up. Here is my designer code:
<asp:LinqDataSource ID="ItemViewDataSource" runat="server" ContextTypeName="GSFyi.GSFyiDataClasses_DataContext"
TableName="FYI_Items" OrderBy="FYI_State.name, name" EnableDelete="True">
</asp:LinqDataSource>
<h2 class="gridTitle">
All Items</h2>
<telerik:RadGrid ID="ItemViewRadGrid" runat="server" AutoGenerateColumns="False"
DataSourceID="ItemViewDataSource" GridLines="None" AllowAutomaticDeletes="True"
EnableEmbeddedSkins="False" OnItemDataBound="itemsGrid_ItemDataBound"
AllowPaging="True" PageSize="15" AllowCustomPaging="True">
<HeaderContextMenu>
<CollapseAnimation Type="OutQuint" Duration="200"></CollapseAnimation>
</HeaderContextMenu>
<PagerStyle FirstPageImageUrl="../../../../../Custom/Modules/GSFyi/Resources/Images/Icons/resultset_first.png"
LastPageImageUrl="../../../../../Custom/Modules/GSFyi/Resources/Images/Icons/resultset_last.png"
Mode="NextPrev"
NextPageImageUrl="../../../../../Custom/Modules/GSFyi/Resources/Images/Icons/resultset_next.png"
PrevPageImageUrl="../../../../../Custom/Modules/GSFyi/Resources/Images/Icons/resultset_previous.png" />
<MasterTableView DataKeyNames="id" DataSourceID="ItemViewDataSource" CommandItemDisplay="None"
CssClass="listItems" Width="98%" PageSize="15" PagerStyle-Mode="NextPrevAndNumeric">
<RowIndicatorColumn>
<HeaderStyle Width="20px" />
</RowIndicatorColumn>
<ExpandCollapseColumn>
<HeaderStyle Width="20px" />
</ExpandCollapseColumn>
<Columns>
<telerik:GridTemplateColumn ItemStyle-CssClass="gridActions edit" UniqueName="Edit">
<ItemTemplate>
<asp:HyperLink ID="edit" runat="server" Text="Edit"></asp:HyperLink>
</ItemTemplate>
<ItemStyle CssClass="gridActions edit"></ItemStyle>
</telerik:GridTemplateColumn>
<telerik:GridButtonColumn ConfirmText="Are you sure you want to delete this item?"
ConfirmDialogType="RadWindow" ButtonType="LinkButton" ItemStyle-CssClass="gridActions delete"
CommandName="Delete">
<ItemStyle CssClass="gridActions delete"></ItemStyle>
</telerik:GridButtonColumn>
<telerik:GridBoundColumn DataField="name" HeaderText="Item Name" SortExpression="name"
UniqueName="name">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn HeaderText="State" UniqueName="state" >
<ItemTemplate>
<asp:Literal ID="stateLit" runat="server" Text='<%# Eval("FYI_State.name") %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Type" UniqueName="type">
<ItemTemplate>
<asp:Literal ID="typeLit" runat="server" Text='<%# Eval("FYI_Type.name") %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="url" HeaderText="Value" SortExpression="url" UniqueName="url">
</telerik:GridBoundColumn>
</Columns>
<EditFormSettings>
<EditColumn InsertImageUrl="Update.gif" UpdateImageUrl="Update.gif" EditImageUrl="Edit.gif"
CancelImageUrl="Cancel.gif">
</EditColumn>
</EditFormSettings>
</MasterTableView>
<FilterMenu>
<CollapseAnimation Type="OutQuint" Duration="200"></CollapseAnimation>
</FilterMenu>
</telerik:RadGrid>
I assumed that AT LEAST the images would be present since I specified these images:
But no luck. Any input will be greatly appreciated!
Cheers,
anders
Most probably the (embedded) skin CSS files have failed to load. You can use Fiddler or Firebug to check your web site for failing requests. I have a blog post showing how to troubleshoot and resolve such problems. You can check it here
Indeed the odd appearance of the grid is due to the default skin not loading. This is because you have set EnableEmbeddedSkins="False". I assume you want the 'Default' skin because you have not specified one. Remove this declaration or set it to true. The odd combobox layout is due to the lack of the skin.
The images not loading is probably unrelated to the skin not loading. I'd check the path to the images.

Categories

Resources