Get values from DataTable without data binding to UI controls? - c#

I always get values from the database directly to a control like this:
Code-behind:
DataTable table = GetUserInfo();
UserInfo.DataSource = table;
UserInfo.DataBind();
string FirstName = lblFirstName.Text;
string LastName = lblLastName.Text;
DateTime BecomeAMember = DateTime.Parse(lblBecomeAMember.Text);
Markup:
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("FirstName") %>' />
<asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName") %>' />
<asp:Label ID="lblBecomeAMember" runat="server" Text='<%# Eval("BecomeAMember", "{0:dd MMM yyy) %>' />
There has to be a way to use the data in code-behind without putting it to a label and then use String text = label.Text;
I need the minutes and hours from BecomeAMember, and I don't want to use another Label with the full DateTime and make it invisible. It would be nice to know how to get the other values as well.

You may use DataTable methods to read values directly from the table object.
For instance,
string firstName = table.Rows[0]["FirstName"].ToString();
or
foreach (DataRow row in table.Rows)
{
//
}
Or use Select() method to search on specified field.
DataRow[] rows = table.Select("column1='value1'");

Yes, you can directly investigate the data held in the DataTable.
DataTable can be made into an IEnumerable, and can be queried. In your case:
var datetimes = table.AsEnumerable().Select(x => x.Field<DateTime>("BecomeAMember"));
If you really only expect a single row, you can do either:
var dt = table.AsEnumerable().Select(x => x.Field<DateTime>("BecomeAMember")).Single();
or:
var dt = (DateTime) table.Rows[0]["BecomeAMember"];
Then format dt using ToString with a format string.

Related

GridView Templatefield date formatting not working

Code on aspx:
<EditItemTemplate>
<asp:TextBox ID="TextBox12" runat="server" Text='<%# Bind("Release_Dt", "{0:yyyy-MM-dd}") %>'></asp:TextBox>
<asp:CustomValidator runat="server" ID="Release_Dt_vdt1"
ControlToValidate="TextBox12" onservervalidate="validate_dt"
ErrorMessage="enter valid date" ValidationGroup="UpdateVdtGrp" ForeColor="Red" Display="Dynamic" SetFocusOnError="true">
</asp:CustomValidator>
</EditItemTemplate>
Validation code (in code behind):
protected void validate_dt(object source, ServerValidateEventArgs args)
{
DateTime minDate = DateTime.Parse("1000/12/28");
DateTime maxDate = DateTime.Parse("9999/12/28");
DateTime dt;
args.IsValid = (DateTime.TryParse(args.Value, out dt)
&& dt <= maxDate
&& dt >= minDate);
}
Question: The date format keeps changing from "yyyy-MM-dd" to short / long date format as shown below every time the row is updated (even just clicking "edit" and "update" on the default gridview buttons without changing any content / dedicated editing 'textbox12'). What is the cause, and how could we fix it?
I have clarify that the SQL database connected to, which this data is stored as string, does not auto-format the data when updated.
If I am missing some piece of important info for the question please advise, thanks in advance.

string.replace databound column in Gridview

Im currently pulling a string comment from a DB into a gridview to display to the user. Throughout the string i have placed <br/>s where i want linebreaks, but am wondering how to replace the <br/>s with "Environment.Newline"s. the column is simply a boundfield.
<Columns>
<asp:BoundField HeaderText="Comment" DataField="UAComment" />
</Columns>
and im populating the table with an adapter and Fill():
adapter = new SqlDataAdapter(queryString, connection);
connection.Open();
adapter.SelectCommand = command;
recordsFound = adapter.Fill(table);
results.Text = recordsFound + " records matching query";
connection.Close();
Thanks for any info.
ps: also tried already building the string/submitting the string to the database with newlines but cant seem to get it to pull out of the db with the proper formatting.
public void Group(String message)
{
log.Append(": Group :");
log.AppendFormat(message);
log.Append("<br/>");
}
public String GetLog()
{
log.Replace("<br/>", Environment.NewLine);
return log.ToString();
}
also substituted "Environment.Newline" with #"\n", "\n", #"\r", "\r"
The easiest solution would be use a template field instead of bound field and add bind a literal in the template field with current column value. Using this it will render all the stuff in html format and the line breaks come autometically.
Example :
<asp:TemplateField>
<HeaderTemplate>
Comment
</HeaderTemplate>
<ItemTemplate>
<asp:Literal runat="server" ID="Literal1" Text='<%# Eval("UAComment") %>' />
</ItemTemplate>
</asp:TemplateField>
Hope this will fix you problem

error handling on page design (source)

I have a control in GridView which converts dateformat From MMddyyyy To ddMMyyyy.
<ItemTemplate>
<asp:Label ID="lblName" runat="server"
Text='<%# Eval("Value1") != DBNull.Value ?
(Convert.ToDateTime(Eval("Value1")).ToString("dd/MM/yyyy")) : Eval("Value1") %>'>
</asp:Label>
</ItemTemplate>
This works perfectly if it gets a date or null value.
But in my case Value1 (the Bind Field) can be a string containing anything. say - 'garbageStr'.
So it fails to convert to date and throws error.
Instead I want to display null or blank value when it fails to convert to DateTime format.
Is there any way to handle this?
you can define a method for this purpose in code behind , and call it, then in method implementation try conversion in DateTime.TryParse and return string accrdingly
In your aspx file:
<asp:Label ID="lblName" runat="server" Text='<%# ReturnPropertDateTime(Eval("Value1")) %>'> </asp:Label>
In your Code Behind file:
protected DateTime ReturnPropertDateTime(object val)
{
DateTime dt = null;
string dateTimeValue = Convert.ToString(val);
DateTime dateTime2;
if (DateTime.TryParse(dateTimeValue.ToString("ddMMyyyy"), out dateTime2))
{
dt = dateTime2;
}
else
{
dt = // Just Assign Default date time value you want.
}
return dt;
}
Although its tedious, but you can make your aspx file more readable through this approach as it prevents clutering and provide flexible handling.

Adding String Array to listView Row Control C# asp.net

This is my first attempt at asp.net and webforms, windowsforms, all of it. I originally populated data in a listbox, but I could only get one column and thought the listView sounded like it would do what I wanted.
The most promising solution I found was this:
DataSet listData = new DataSet();
CancellationsControls cancelCtrl = new CancellationsControls();
listData = cancelCtrl.GetScheduledReleaseDataSet();
DataTable dtable = listData.Tables[0];
scheduledReleasesTag.Items.Clear();
foreach (DataRow row in dtable.Rows)
{
string[] ar = Array.ConvertAll(row.ItemArray, p => p.ToString());
scheduledReleasesTag.Items.Add(new ListViewDataItem(ar));
}
The dtable is a custom table of a query joining a number of tables.
in the foreach loop the ar string array succesfully shows the colums of data that I want, but the ListViewDataItem requires two int arguments instead of a string array like the example I pulled this from.
I've tried to figure out more about how the listView control works, but this is as close as I have been able to get to getting anything. Any help with explanations would be very appreciated.
Thank you :)
I'm pretty beginner in asp, but to bind ListView control with data, smth like this should work:
DataSet listData = new DataSet();
CancellationsControls cancelCtrl = new CancellationsControls();
listData = cancelCtrl.GetScheduledReleaseDataSet();
DataTable dtable = listData.Tables[0];
ListView1.DataSource = dtable;
ListView1.DataBind();
Now we have to create an ItemTemplate. Your ListView control should look like:
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<tr id="Tr1" class="item" runat="server">
<td>
<asp:Label ID="column_name" runat="server" Text='<%# Eval("column_name") %>' />
</td>
</tr>
<tr id="Tr2" class="item" runat="server">
<td>
<asp:Label ID="another_column_name" runat="server" Text='<%# Eval("another_column_name") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Just replace markers(column_name,another_column_name) with names of columns, that contains data you want to display. This template displays pairs of rows values from two columns one by one.

Convert Gridview column from ID to String in ItemTemplate

I currently have a Gridview that displays
TypeID , Name , Description.
I would like to display the actual type name instead of the TypeID in the gridview. I created this function that takes in the ID and returns the Name but I am having trouble using it. There are 15-20 different types so How do I convert the TypeID to a Type Name so that it is displayed when the Gridview is rendered.
protected string GetGenericTypeByID(int genericTypeID)
{
string genericTypeName;
GenericType.Generic_TypeDataTable genericTypeNameDS = new GenericType.Generic_TypeDataTable();
genericTypeNameDS = GenericBO.Get_GenericTypeByID(genericTypeID);
genericTypeName = genericTypeNameDS[0]["Generic_Type_Name"].ToString();
return genericTypeName;
}
I thought I would be able to use the function in the ItemTemplate but it seems to be harder that I thought
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("GetGenericTypeByID("Generic_Type_ID")")%>'></asp:Label>
</ItemTemplate>
Thanks to Everyone who helped me solve this problem.
I ended up using the method below and it works perfectly.
GetGenericTypeByID( Convert.ToInt32(Eval("Generic_Type_ID")))
You've got the 'bind/eval' and method call inside out.
See Using Method inside a DataGrid or GridView TemplateField
<asp:TemplateField HeaderText=”Name”>
<ItemTemplate>
<a href='<%# FormatUrl(Eval(”email1″).ToString())%>'><%# Eval(”fname”) %>, <%# Eval(”lname”) %></a>
</ItemTemplate>
With the 'FormatUrl' function being:
public string FormatUrl(string email)
{
return “mailto:” + email;
}
Are you limited to a label tag? If not, Expanding on David HAust's answer try the following:
<ItemTemplate>
<%#GetGenericTypeByID(Eval(Generic_Type_ID))%>
</ItemTemplate>
Create a read-only property on the row class that you're using to populate the grid, and get this property to return the results of your function.

Categories