Reputation: 1187
Can I update a gridview column's content after databind? The SQL column is a full name, and I need to display it as last name, first name, not first name last name, as it is now. I know that i can do this in sql, but it seems as though it is going to be kind of a pain (SQL: parse the first, middle and last name from a fullname field). I was just wondering if there is an easier way to do this.
Thanks
Ok, I figured it out... sorry. In the event someone else needs this, I added a OnRowDataBound="MailingList_RowDataBound"
event, and within that event handler, I have am going to use the following code (modified to parse the name):
public void MailingList_RowDataBound(object sender, GridViewRowEventArgs e)
{
// Required to ignore the header/footer.
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Get the Person's Name
string name = e.Row.Cells[0].Text;
//Add your JavaScript onClick event link.
e.Row.Attributes.Add("onClick", "LookupEmail('" + name + "')");
e.Row.Cells[0].Text = "Test";
}
}
Changing the "Test" to the correct values.
Upvotes: 1
Views: 5738
Reputation: 19261
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<span>
<%# Eval("FullName").Split(' ')[0]%>
</span>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Surname">
<ItemTemplate>
<span>
<%# Eval("FullName").Split(' ')[1]%>
</span>
</ItemTemplate>
</asp:TemplateField>
This should solve your problem. Assuming the column name is FullName
in your database and the first name and surname are seperated with space, you can split those and bind each value to different columns in GridView
.
Upvotes: 2
Reputation: 6612
use itemtemplate
<asp:GridView ID="tset" runat="server">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="label1" runat="server" Text='<%#GetFormattedName(Eval("full_name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and write GetFormattedName method in code behind to return a string however you want,
protected string GetFormattedName(string fullName)
{
// you can split full name here and swap first name, last name
// depending on how you store it in DB
}
Upvotes: 2