<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?
Related
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?
I have a GridView that has data bounded rows. I'm trying to get specific cell value on the SelectedIndexChanged event of DropDownList. My tries are as follows:
string temp= GridView2.SelectedRow.Cells[3].Text;
string temp = ((DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0]).Text;
DataBoundLiteralControl dblc = (DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0];
string temp=dblc.Text;
These all 3 of them returns null.
Moreover, the Control[0] is returning correct value of TemplateFields only, but not DataBound fields.
.aspx
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #d54d7b" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging" Width="900px" Font-Names="Segoe UI Light" BorderColor="#DEDEDE">
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="80" />
<asp:BoundField DataField="Vacancies" HeaderText="Vacancies" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Detail">
<ItemTemplate>
<asp:BoundField DataField="Date" HeaderText="Date" ItemStyle-Width="80" />
<asp:BoundField DataField="Time" HeaderText="Time" ItemStyle-Width="80" />
</Columns>
Problem you are probably facing is that, GridView1 hasn't been bounded yet.. that is the reason why Control[0] is returning correct value of TemplateFields but cells in the gridview returns null.
You can do the following
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
/// send value to filter or bind gridView1
/// bind gridvew
string temp = GridView1.Rows[0].Cells[3].Text;
/// or any code to get values from GridView Cell
}
I Converted all <asp:BoundFields> to <asp:TemplateField> and it looked like this:
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #009C0D" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" CssClass="test"
HtmlEncode="true"
Font-Names="Segoe UI Light" BorderColor="#DEDEDE" >
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:TemplateField HeaderText="Description" ControlStyle-Width="250px" ><ItemTemplate> <asp:LinkButton ID= "Description" PostBackUrl='<%# Eval("Description", "~/{0}.aspx") %>' Text='<%# Eval("Description")%>' runat="server" ></asp:LinkButton> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Vacancies"><ItemTemplate> <asp:Label ID="Vacancies" Text='<%# Eval("Vacancies")%>' runat="server" ></asp:Label> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Detail"><ItemTemplate><asp:Label ID="City" Text='<%# Eval("City")%>' runat="server" ></asp:Label> <div style="font-size:10px"> <asp:Label ID="Label1" Text='<%# Eval("DateDay")%>' runat="server" ></asp:Label> </div> </ItemTemplate></asp:TemplateField>
//and others
</Columns>
</asp:GridView>
And get specific value by entering this code behind DropDownList:
if (dropdown.SelectedIndex != -1)
{
ListItem mySelectedItem = (from ListItem li in dropdown.Items where li.Selected == true select li).First();
foreach (GridViewRow rw in GridView2.Rows)
{
Label tv = (Label)rw.Cells[3].FindControl("City");
if (tv.Text.IndexOf(mySelectedItem.Text) != -1)
{
rw.Visible = true;
}
else
rw.Visible = false;
}
}
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]);
}
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())%>' />
<asp:GridView ID="gvStates" AutoGenerateColumns="false" Width="100%" AllowSorting="true"
runat="server" OnRowCreated="gvStates_RowCreated"
OnRowDataBound="gvStates_RowCreated">
<HeaderStyle BackColor="#57768f" ForeColor="White" />
<RowStyle BackColor="#dae2e8" ForeColor="Black" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="#ffffff" ForeColor="Black" />
<Columns>
<asp:BoundField HeaderText="key" DataField="key" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Quota" DataField="Quota" />
<asp:BoundField HeaderText="Session" DataField="Sess" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:DropDownList ID="ddlSess" Width="100%" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddl">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Scheduled">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%#Bind("Sched")%>' Enabled="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%#Bind("Sched")%>' />
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button ID="_b_SchStat" runat="server" AutoPostBack="true" Text="UnSchedule" OnClick="_b_ToggleSched" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Recruiter">
<ItemTemplate>
<asp:DropDownList ID="ddRec" Width="100%" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddR">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="MN Phone" DataField="MN Phone" />
<asp:BoundField HeaderText="Cell Phone" DataField="Cell Phone" />
</Columns>
</asp:GridView>
[dbo].[QRY_RecruitGrid]
#jobnum varchar(20),
#quota varchar(10),
#sess VARCHAR(10)
AS
SELECT
[job_resp_recordid] as 'key'
,[job_resp_name] as 'Name'
,[job_resp_quota] as 'Quota'
,[job_resp_session] as 'Sess'
,[job_resp_scheduled] as 'Sched'
,COALESCE([job_resp_recruited_by], '') as 'Recruiter'
,case when len(ltrim(rtrim([job_resp_phone])))='10' then '('+SUBSTRING([job_resp_phone],1,3)+')'+' '+SUBSTRING([job_resp_phone],4,3)+'-'+SUBSTRING([job_resp_phone],7,4) when len(ltrim(rtrim([job_resp_phone])))='' then ' ' end AS [MN Phone]
,case when len(ltrim(rtrim([job_resp_cellphone])))='10' then '('+SUBSTRING([job_resp_cellphone],1,3)+')'+' '+SUBSTRING([job_resp_cellphone],4,3)+'-'+SUBSTRING([job_resp_cellphone],7,4) when len(ltrim(rtrim([job_resp_cellphone])))='' then ' ' end AS [Cell Phone]
FROM [dbo].[tbl_job_respondents]
WHERE job_resp_job_number like #jobnum
and job_resp_quota like #quota
AND job_resp_session LIKE #sess
order by job_resp_quota, [job_resp_name]
I'm trying to bind the 'ddRec' dropdown to the Recruiter field in the dataset. I tried
DataTextField='<%#Bind("Recruiter")%>'
Edit:
Error: {"Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control."}
Let me explain better sorry. I'm trying to set the value from the proc but the dropdown list itself is being populated from a query on the OnRowCreated Event I think this is my problem
protected void gvStates_RowCreated(object sender, GridViewRowEventArgs e)
{
var drop = new List<string> { "" };
var LNQ = new LNQDataContext();
var Rec = LNQ.Recruits.Where(c => c.Active == "Y").Select(c => new { c.Name });
var Rdp = new List<string> { "" };
foreach (var a in Rec) { Rdp.Add(a.Name); }
for (int i = 1; i <= _cnt; i++) { drop.Add("S" + i); }
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = (DropDownList)e.Row.FindControl("ddlSess");
ddl.DataSource = drop;
ddl.DataBind();
var ddR = (DropDownList)e.Row.FindControl("ddRec");
ddR.DataSource = Rdp;
ddR.DataBind();
}
}
You can't programmatically bind to the DataTextField field; the DataTextField identifies the field to display in the drop down, hence it has to be static and is not evaluated per row. Though, you can tap into the Grid's RowDataBound event, and programmably set the DataTextField property and bind data at that point.
HTH.