show data in gridview only some words - c#

I'm use grid view for show recent messages...there use datasource...
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" Width="586px" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:CommandField HeaderText="show" ShowSelectButton="True" />
<asp:BoundField DataField="user_id" HeaderText="user_id"
SortExpression="user_id" />
<asp:BoundField DataField="user_name" HeaderText="user_name"
SortExpression="user_name" />
<asp:BoundField DataField="sender_mail" HeaderText="sender_mail"
SortExpression="sender_mail" />
<asp:BoundField DataField="message" HeaderText="message" ReadOnly="True"
SortExpression="message" ControlStyle-Width="70px" ControlStyle-Height="25">
<ControlStyle Height="20px" Width="50px" />
<HeaderStyle Height="10px" Width="70px" />
<ItemStyle Height="20px" HorizontalAlign="Left" Width="70px" />
</asp:BoundField>
</Columns>
</asp:GridView>
there in my database if message is too long then it show in one field...
ex:-msg is 'hi how are you'
it show full msg......but i show data only 'hi how...'
i'm also try set width and height but not work.

You can use a template field instead of the boundfield.
<asp:TemplateField >
<HeaderTemplate>Message</HeaderTemplate>
<ItemTemplate>
<%# Eval("message").ToString().Substring(0,10) %>
</ItemTemplate>
<EditItemtemplate>
<asp:textbox id="Textbox1"
text='<%#Eval("message")%>'
width="90"
runat="server"/>
</Edititemtemplate>
</asp:TemplateField>
Here we are taking a substring of the message (10 characters only). you can modify to suit your needs.

You can do this by adding method to your code that take the msg from DB or just string then you make on that string whatever you want(cut the string at specific index then add ...). And that method then return the processed string back
public string cutString(string msg)
{
int msgLength = 100;
return msg.Substring(0, msgLength) + "...";
}
<asp:Label runat="server" Text='<%# cutString(Eval("message").ToString())%>' />

Related

How to get the selected value of a dropdownlist in a Gridview C#

I'm having a GridView to display few columns. when I click the edit button in the GridView, it displays a DropDownList for one column which has a list of values to select.
I need to select a value and click on the Update button to update the database with the latest selected value.
<asp:GridView ID="GrdAttributesView" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" CssClass="well"
EmptyDataText="No Records to display."
OnPageIndexChanging="GrdAttributesView_PageIndexChanging"
OnRowCancelingEdit="GrdAttributesView_RowCancelingEdit"
OnRowEditing="GrdAttributesView_RowEditing"
OnRowUpdated="GrdAttributesView_RowUpdated"
OnRowUpdating="GrdAttributesView_RowUpdating"
OnSelectedIndexChanged="GrdAttributesView_SelectedIndexChanged"
OnSorting="GrdAttributesView_Sorting"
OnRowDeleting="GrdAttributesView_RowDeleting"
OnRowDeleted="GrdAttributesView_RowDeleted"
OnRowDataBound="GrdAttributesView_RowDataBound" PagerSettings-Mode="Numeric"
PagerStyle-Font-Bold="true" PageSize="20" ShowHeaderWhenEmpty="True">
<Columns>
<%-- <asp:TemplateField HeaderText="Globalized Indicator">
<ItemTemplate>
<asp:CheckBox ID="Chk_GlobalizedIndicatorGrid" runat="server" Width="55px" OnCheckedChanged="Chk_GlobalizedIndicatorGrid_CheckedChanged" Text='<%# Eval("GlobalizedInd") %>' Checked ='<%# Eval("GlobalizedInd") == DBNull.Value ? false : Convert.ToBoolean(Eval("GlobalizedInd")) %>' Enabled="false"/>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:CommandField HeaderText="Edit Record" ItemStyle-Width="150px" ShowEditButton="True" ShowHeader="True" ShowDeleteButton="true">
<ItemStyle Width="100px" />
</asp:CommandField>
<asp:BoundField HeaderText="Added Date" DataField="AddedDate" ItemStyle-Width="700px" ReadOnly="true" ControlStyle-Width="700px">
<ControlStyle Width="200px"></ControlStyle>
<ItemStyle Width="200px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Created By" DataField="CreatedBy" ItemStyle-Width="700px" ReadOnly="true" ControlStyle-Width="700px">
<ControlStyle Width="100px"></ControlStyle>
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Ticket Number" DataField="TicketNumber" ItemStyle-Width="200px" ReadOnly="true" ControlStyle-Width="700px">
<ControlStyle Width="200px"></ControlStyle>
<ItemStyle Width="200px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Ticket URL" DataField="TIcketURL" ItemStyle-Width="200px" ReadOnly="true" ControlStyle-Width="700px">
<ControlStyle Width="600px"></ControlStyle>
<ItemStyle Width="600px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Hours Spent" ItemStyle-Width="100px" ControlStyle-Width="700px">
<ControlStyle Width="100px"></ControlStyle>
<ItemStyle Width="100px"></ItemStyle>
<ItemTemplate>
<asp:Label ID="LblHoursSpent" runat="server" Text='<%# Eval("HoursSpent")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="LblHoursSpent" runat="server" Text='<%# Eval("HoursSpent")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="CmbHoursSpent" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Minutes Spent" ItemStyle-Width="100px" ControlStyle-Width="700px">
<ControlStyle Width="120px"></ControlStyle>
<ItemStyle Width="120px"></ItemStyle>
<ItemTemplate>
<asp:Label ID="LblMinutesSpent" runat="server" Text='<%# Eval("MinutesSpent")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="LblMinutesSpent" runat="server" Text='<%# Eval("MinutesSpent")%>' Visible="false"></asp:Label>
<%--<asp:DropDownList ID="CmbHoursSpent" AppendDataBoundItems="true" DataTextField="NumberofHoursSpent" DataValueField="HoursSpent" AutoPostBack="false" runat="server" OnSelectedIndexChanged="CmbHoursSpent_SelectedIndexChanged" enabled="true">
</asp:DropDownList>--%>
<asp:DropDownList ID="CmbMinutesSpent" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle Font-Bold="True" />
</asp:GridView>
The code behind is as follows:
protected void GrdAttributesView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && GrdAttributesView.EditIndex == e.Row.RowIndex)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlHours = (DropDownList)e.Row.FindControl("CmbHoursSpent");
ddlHours.DataSource = GenerateHoursList();
ddlHours.DataTextField = "NumberofHoursSpent";
ddlHours.DataValueField = "HoursSpent";
ddlHours.DataBind();
ddlHours.Items.FindByValue((e.Row.FindControl("LblHoursSpent") as Label).Text).Selected = true;
DropDownList ddlMinutes = (DropDownList)e.Row.FindControl("CmbMinutesSpent");
ddlMinutes.DataSource = GenerateMinutesList();
ddlMinutes.DataTextField = "NumberofMinutesSpent";
ddlMinutes.DataValueField = "MinutesSpent";
ddlMinutes.DataBind();
ddlMinutes.Items.FindByValue((e.Row.FindControl("LblMinutesSpent") as Label).Text).Selected = true;
}
}}
protected void GrdAttributesView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddlprice = (DropDownList)GrdAttributesView.Rows[e.RowIndex].FindControl("CmbHoursSpent");
String value = ddlprice.SelectedValue;
string MinutesSpent = (GrdAttributesView.Rows[e.RowIndex].FindControl("CmbMinutesSpent") as DropDownList).SelectedItem.Value;
}
Ideally in the RowUpdating method I should get the new value from the DropDown. but I don't understand why it gives the old value even though I select a different value.
I did a lot of reading and I saw different people using the same approach to get it done. But somehow it is not working for me.
Can someone help please?

Passing values from GridView to code behind file in ASP.NET

I have a GridView that binds values from the database.
Here is the code:
<asp:GridView ID="GridView1" AutoGenerateColumns="False" DataKeyNames="DataView" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="Title" />
<asp:ImageField DataImageUrlField="ProductId" DataImageUrlFormatString="getProductImage.ashx?ProductID={0}" HeaderText="Image">
</asp:ImageField>
<asp:BoundField DataField="ProductDescription" HeaderText="Description" />
<asp:BoundField DataField="ProductCost" HeaderText="Cost" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox runat="server" TextMode="Number" ID="txtQuantity"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Button" CommandName="AddToCart" />
</Columns>
</asp:GridView>
I want to pass the command arguments containing values from txtQuantity and ProductID to the code behind on CommandName "AddToCart".
How can I do this?
Bind the values of the ProductID & Quantity in the GridView. In GridView, give like this:
<asp:GridView ID="GridView1" AutoGenerateColumns="False" DataKeyNames="DataView" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="Title" />
<asp:ImageField DataImageUrlField="ProductId" DataImageUrlFormatString="getProductImage.ashx?ProductID={0}" HeaderText="Image">
</asp:ImageField>
<asp:BoundField DataField="ProductDescription" HeaderText="Description" />
<asp:BoundField DataField="ProductCost" HeaderText="Cost" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox runat="server" TextMode="Number" ID="txtQuantity" Text="<%# Bind("Quantity")%>"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:Button Text="Button" CommandName="AddToCart" CommandArgument="<%# Eval("Quantity") + "," + Eval("ProductID")%>" />
</Columns>
</asp:GridView>
In GridView RowCommand event, give the below code:
if(e.CommandName == "AddToCart")
{
string[] args = e.CommandArgument.ToString().Split(",");
Decimal Quantity = Convert.ToDecimal(args[0]);
int ProductID = Convert.ToInt32(args[1]);
}

GridView affected by window.open

I have a gridView which works nicely until I open a new window by clicking a button. When the new window is opened the values in one of the columns 'lblTotalPrice' gets erased. 'lblTotalPrice' is a template field, which is calculated in MealList_RowDataBound (quantity * price). The footer for the column, however is not affected when the new window is opened (also gets its value in MealList_RowDataBound).
Also the font-size of the data-bound columns are changed when the new window is opened.
Any ideas of what might cause this? When stepping through the code there are no other lines executed after btnEnvComment_Click
When gridView is databound again, everything is back to normal.
The gridView:
<rwg:BulkEditGridView ID="MealList" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="Vertical" CellPadding="4"
BackColor="White" DataKeyNames="ItemId,ProductId" SaveButtonID="SaveButton"
DataSourceID="SqlMealItems" style="float:left"
OnRowDataBound="MealList_RowDataBound" OnRowCreated="MealList_RowCreated" CssClass="gridView">
<AlternatingRowStyle CssClass="MealListItemAlt" BackColor="#a6dbed" />
<Columns>
<asp:BoundField DataField="ProductId" HeaderText="Prod #" HeaderStyle-Wrap="false" ReadOnly="True" >
<HeaderStyle Wrap="False" Width="60px"></HeaderStyle>
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
<asp:BoundField DataField="ProductName" HeaderText="Namn" ReadOnly="True" ItemStyle-Wrap="False" >
<ItemStyle Width="150px" />
</asp:BoundField>
<asp:BoundField DataField="Quantity" HeaderText="Antal" ControlStyle-CssClass="numeric" >
<ControlStyle CssClass="numeric" Width="30px"></ControlStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Enhet">
<ItemTemplate>
<asp:DropDownList ID="DropDownUnit" OnSelectedIndexChanged="DropDownUnit_SelectedIndexChanged"
AutoPostBack="False" runat="server" DataTextField="Unit" DataValueField="Unit">
</asp:DropDownList>
</ItemTemplate>
<ControlStyle Width="70px" />
</asp:TemplateField>
<asp:BoundField HeaderText="á pris" ReadOnly="True" ControlStyle-CssClass="rightAlign" ItemStyle-Wrap="False">
<ControlStyle CssClass="numeric" ></ControlStyle>
<ItemStyle HorizontalAlign="Right" Width="80px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Totalt" ItemStyle-Wrap="False">
<ItemTemplate>
<asp:label ID="lblTotalPrice" runat = server></asp:label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" Width="80px" />
<FooterTemplate>
<asp:Label ID="lblTotalPricePerMeal" runat="server"></asp:Label>
</FooterTemplate>
<FooterStyle HorizontalAlign="Right" Font-Bold="true" Font-Overline="True" Wrap="False" />
</asp:TemplateField>
<asp:BoundField DataField="Unit" HeaderText="h" ReadOnly="True" />
<asp:TemplateField>
<ItemTemplate>
<asp:image runat="server" ID="imgBlob" Width="24"></asp:image>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="lblError"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle CssClass="MealListFooter" />
<HeaderStyle CssClass="MealListHead" />
</rwg:BulkEditGridView>
The code for the button that open the new window:
protected void btnEnvComment_Click(object sender, EventArgs e)
{
int offsetPos = 125; // set placement of new window
String URL = "EnvComment.aspx?MealID=" + Session["MealId"];
String responsCommand = "window.open('" + URL + "','_blank','height=400,width=300,top=" + ",left=" + offsetPos.ToString() + offsetPos.ToString() + ",titlebar=1')";
Response.Write("<script>");
Response.Write(responsCommand);
Response.Write("</script>");
}

Sorting and paging GridView issues

i'm using a GridView and trying to sort and page it.
I have more than 20 rows on my DataBase, but the GridView just shows 10.
I set AllowPaging=true but noting happened.
Also I'm using AllowSorting = true and OnSorting="GridView_Sorting". But when I click on the header to sort the the content of that column, it does not enters on my OnSorting="GridView_Sorting" it goes right to the GridView1_RowCommand why ?
Sometimes it just give me this error:
Object reference not set to an instance of an object error
Here's my Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" style="font-family: Verdana, Arial, Sans-Serif;"
CssClass="gridview" OnSorting="GridView_Sorting"
AllowSorting ="True" AllowPaging="True" BackColor="#CCCCCC"
BorderStyle="Inset" BorderWidth="2px" BorderColor="GrayText"
CellPadding="1"
CellSpacing="5"
HeaderStyle-HorizontalAlign="Center"
OnRowDataBound="GridView1_RowDataBound"
ForeColor = "Black" RowStyle-CssClass="gridview"
OnRowCommand="GridView1_RowCommand">
<AlternatingRowStyle BackColor="#CCCCCC" />
<columns>
<asp:BoundField HeaderText="ID" DataField="id" SortExpression="id" />
<asp:BoundField HeaderText="PRIORIDADE" DataField="prioridade" ItemStyle-HorizontalAlign="Center" SortExpression="prioridade" SortExpression="prioridade" />
<asp:BoundField HeaderText="SITUAÇÃO" DataField="situacao" ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="RESPONSAVEL" DataField="responsavel" HeaderStyle-Width="65px" ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="65px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="DATA DE CADASTRO" DataField="dt_cadastro" SortExpression="dt_cadastro" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"ItemStyleHorizontalAlign="Center" >
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="PREVISÃO DE TÉRMINO" DataField="previsao_termino" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"
ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="PROJETO" DataField="projeto" ItemStyle-HorizontalAlign="Center"></asp:BoundField>
<asp:BoundField HeaderText="FUNCIONALIDADE" DataField="funcionalidade" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="CLUBE" DataField="clube" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderStyle-Width="70px" HeaderText="VISUALIZAR" >
<ItemTemplate>
<asp:Button ID="Btn_Visualizar" runat="server" Text="VISUALIZAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial" OnClick="Btn_Visualizar_Click"CommandName="visualizar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="66px" HeaderText="ALTERAR">
<ItemTemplate>
<asp:Button ID="Btn_Alterar" runat="server" Text="ALTERAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial"CommandName="editar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="66px" HeaderText="FEEDBACK">
<ItemTemplate>
<asp:Button ID="Btn_Feedback" runat="server" Text="ADICIONAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana,Arial"CommandName="feedback" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</columns>
My CodeBehind:
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
string[] strSortExpression = ViewState["SortExpression"].ToString().Split(' ');
// If the sorting column is the same as the previous one,
// then change the sort order.
if (strSortExpression[0] == e.SortExpression)
{
if (strSortExpression[1] == "ASC")
{
ViewState["SortExpression"] = e.SortExpression + " " + "DESC";
}
else
{
ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
}
}
// If sorting column is another column,
// then specify the sort order to "Ascending".
else
{
ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
}
// Rebind the GridView control to show sorted data.
GridView1.DataSource = ch.BuscaTodosChamados();
GridView1.DataBind();
}
Add SortExpression attribute for each sortable column, informing its DataField.

work with grid view

<asp:GridView ID="gridInboxMessage" runat="server"
AutoGenerateColumns="False"
DataSourceID="LinqDataSource1">
<Columns>
<asp:BoundField DataField="Title" HeaderText="title" ReadOnly="True" SortExpression="Title" />
<asp:BoundField DataField="Body" HeaderText="body" ReadOnly="True" SortExpression="Body" />
<asp:BoundField DataField="Sender" HeaderText="sender" ReadOnly="True" SortExpression="Sender" />
<asp:BoundField DataField="Date1" HeaderText="date" ReadOnly="True" SortExpression="Date1" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataClassesDataContext"
Select="new (Title, Body, Sender, Date1)"
TableName="PrivateMessages"
Where="Receptor == #Receptor">
<WhereParameters>
<asp:QueryStringParameter Name="Receptor" QueryStringField="idCompany" Type="String" />
</WhereParameters>
</asp:LinqDataSource>
I have an asp:GridView populated from an LinqDataSource. My questions are
Body included is 1000 characters I can display only 50 characters in the field of body(over flow hide).
field date content 1/1/2011 i want show jul 1 2011 in field date
field sender equal id (example 23) i want show name(23=alen)
How will I achieve all these?
Edit
answer #naveen is correct.
i want when user click on row show body full????
Try this.
Markup
<asp:GridView ID="gridInboxMessage" runat="server"
AutoGenerateColumns="False"
DataSourceID="LinqDataSource1">
<Columns>
<asp:BoundField DataField="Title" HeaderText="title" ReadOnly="True" SortExpression="Title" />
<asp:TemplateField HeaderText="Body" SortExpression="Body">
<ItemTemplate>
<asp:Label ID="MyBody" runat="server"
Text='<%# TruncateText(Eval("Body"))%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sender">
<ItemTemplate>
<asp:Label ID="MySender" runat="server"
Text='<%# GetSenderNameFromID(Eval("Sender"))%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date" SortExpression="Date1">
<ItemTemplate>
<asp:Label ID="MyDate" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "Date1", "{0:MMMM d yyy}")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
protected string TruncateText(object objBody)
{
string truncated = "";
if (objBody != null)
{
truncated = objBody.ToString().Length > 50 ?
objBody.ToString().Substring(0, 47) + "..." : objBody.ToString();
}
return truncated;
}
protected string GetSenderNameFromID(object objSenderID)
{
string senderName = "";
if (objSenderID != null)
{
senderName = CallDatabaseToGetNameFromID();
}
return senderName;
}
private string CallDatabaseToGetNameFromID()
{
//implement your database call to retrieve sender name from id
throw new NotImplementedException();
}
Hope this helps.
First of all, if you want to show the Name of sender and not ID, you have to modify your query to join in the table that contains the name
For date issue, you can use Format(Date, "dd/mm/yyyy")
Can you ensure that your query actually returns all the characters before binding to the grid?

Categories