Manipulate SQL values before displaying on GridView - c#

N,V,C,D are the variables in a bound column of my GridView.
When I display this table in my GridView, I want New,Verified,Cancelled,Deleted to be displayed instead.
My GridView calls a procedure in my database that runs the select Query. Do I need to change the query or add a GridView function? I do not want to change my database values per se.
How do I go about this?
This is my bound field as of now:
<asp:BoundField
DataField="Status"
HeaderText="Status"
SortExpression="Status" />

That should be possible in C# - at least if you only wan to display the values and not edit them. In the CellFormatting event you can simply change the value to be displayed.
private void gridview_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.Value.equals("N")) e.Value = "New";
else if(e.Value.equals("V")) e.Value = "Verified";
else if(e.Value.equals("C")) e.Value = "Cancelled";
else if(e.Value.equals("D")) e.Value = "Deleted";
}
I haven't got C# at hand right now, so there may be typos. Just try it.

In your query,
Select
YourFields
case
when YourConditionField= 'N' then 'New'
when YourConditionField= 'V' then 'Verified'
when YourConditionField= 'C' then 'Cancelled'
when YourConditionField= 'D' then 'Deleted'
end,
from table
First in GridView,
You can use the RowDataBound event, You need to add a template column with a label to your grid view
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="labelResult" runat="server" />
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
string value = e.Row.Cells[0].Text;
Next find the label in the template field.
Label myLabel = (Label) e.Row.FindControl("myLabel");
if (value == "N")
{
myLabel.Text = "New";
}
else if (value == "V")
{
myLabel.Text = "Verified";
}
else if (value == "C")
{
myLabel.Text = "Cancelled";
}
else if (value == "D")
{
myLabel.Text = "Deleted";
}
}
}

<asp:BoundField HeaderText="NEW" DataField="N" ></asp:BoundField>

First, I edited the status column of the GridViewControl from the default BoundField and changed it to ItemTemplate
(I removed the autogenerated EditItemTemplate tag)
<asp:Label ID="lblStatus"
runat="server"
Text='<%# GetLabelText(Eval("status")) %>'>
</asp:Label>
Then in my CS file, I added the following code:
public string GetLabelText(object dataItem)
{
string text = "";
string val = dataItem as string;
switch (val)
{
case "N": text = "New";
break;
case "V": text = "Verified";
break;
case "F": text = "Fulfilled";
break;
case "C": text = "Cancelled";
break;
}
return text;
}
This worked like a charm. Thanks for the help, guys!

Related

Remove ddl's that has no value's

I have little problem. I'm dynamically populating grid view from the values from the database. I'm trying to remove DropDownList's that don't have any values.
I have this code for now:
if (ddlMyDropDown.Items.Count == 0)
{
ddlMyDropDown = false;
}
else
{
ddlMyDropDown = true;
}
<asp:TemplateField HeaderText="Opis">
<ItemTemplate>
<asp:DropDownList ID="ddlMyDropDown" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
This code works fine but it has one problem. It doesn't remove first ddl in column who is also empty but it removes every other after.
Is there any way to select first ddl who si dinamically loaded in the column and set it to visible false ?
Or some foreach loop that eliminates the ddl's with empty value better ?
Can someone help me ?
Thanks in advance !
You can do this.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl =e.Row.FindControl("ddlMyDropDown") as DropDownList;
if (ddl.Items.Count == 0)
{
ddl.Visible = false;
}
else
{
ddl.Visible = true;
}
}
}

How can I Format the gridview column to display 2 decimalplaces from code behind?

I am trying to format my Gridview columns to display decimal values upto 2 places after the decimal point.
I am aware of both DataFormatString='{0:0.00} for the boundfield and also Eval("NumFailedFiles", "{0:0.00}") for ItemTemplate.
But i want this to be configurable, i.e. i want to get the no. of decimal places from the database and apply to the boundfield or itemtemplate.
For acheiving this i have tried formatting in gridview_RowDataBound Event but in vain.
GridDecimal = Convert.ToInt32(resXResourceSet.GetString("GridMaxDecimals"));
var field = gridView.Columns[1] as BoundField;
field.DataFormatString = "{0:0.00}";
With this code i am encountering an exception which says
"Object reference not set to an instance of an object"
at the 3rd line of the above code.
Can someone help me on how to achieve this for both boundfield and Itemtemplate
This is my datasource to clear the ambiguity
My data source:
You could use the DataBound event which is triggered once after the grid was databound. For example (depends on the actual datasource of your grid):
protected void GridView_DataBound(Object sender, EventArgs e)
{
GridView grid = (GridView)sender;
BoundField col = (BoundField)grid.Columns[1];
int numDecimals = 2; // from database
col.DataFormatString = "{0:N" + numDecimals + "}";
}
If you have a TemplateField use RowDataBound, you should use a lazy-load property like following to avoid that the value has to be loaded for every row:
private int? _NumDecimals;
private int NumDecimals
{
get
{
if (!_NumDecimals.HasValue)
_NumDecimals = GetNumDecimalsFromDB();
return _NumDecimals.Value;
}
set
{
_NumDecimals = value;
}
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// if following doesnt work use the debugger to see the type of e.Row.DataItem
DataRow row = ((DataRowView)e.Row.DataItem).Row;
int numFailedFiles = row.Field<int>("NumFailedFiles");
//presuming that your TemplateField contains a Label with ID="LblNumFailedFiles"
Label LblNumFailedFiles = (Label)e.Row.FindControl("LblNumFailedFiles");
string formatString = String.Format("N{0}", NumDecimals);
LblNumFailedFiles.Text = numFailedFiles.ToString(formatString);
}
}
OnRowDataBound of GridView you have to determine which row type you want to custom like header row, data row, and so on. and also RowDataBound event is raised for every row so you need to access specific row with specific column not gridview .
Solutions 1: If Boundfield is binded with data
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Fetching BoundField Value.
double dbvalue =Convert.ToDouble(e.Row.Cells[ColumnNumber].Text);
e.Row.Cells[ColumnNumber].Text = String.Format("{0:0.00}",dbvalue );
Label lblnum = (Label)e.Row.Cells[ColumnNumber].FindControl("labelID");
lblnum.Text = String.Format("{0:0.00}", integervaluetoformat);
}
}
Solutions 2: (If the Column is a Item Field Template)
In case of ItemTemplate Field no need to fire RowDataBound:
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblnum" runat="server" Text='<%# String.IsNullOrEmpty(Eval("dbcolumn").ToString()) ? "" : string.Format("{0:0.00}",Convert.ToDouble(Eval("dbcolumn").ToString())) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

How do I replace a Hyperlink in a Gridview Column with an image, depending on the text in the column?

Question pretty much says it all. On my aspx page I have a GridView and under Columns I have a bunch of BoundFields, one of which is a TemplateField
<asp:TemplateField HeaderText = "Status">
<ItemTemplate>
<asp:HyperLink ID = "HyperLink1" runat = "server" Target = "_blank"
NavigateUrl = '<%# Eval("URL") %>'
Text = '<%#Eval("Status") %>'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
Now, I want this Hyperlink to map to a different image, depending on what the text is evaluated to. For example, 'Success' displays a big ol' smiley face instead, 'Failed' displays a frowney face, and so on. How can I achieve this?
Thanks for looking.
You can put an image in the hyperlink like
<img src='/images/status/<%#Eval("Status") %>.jpg' />
and just make a different image for each status by name. Otherwise you'll probably have to do something on the DataBind event.
Try this
protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink HyperLink1 = e.Row.FindControl("HyperLink1");
if(SomeText == "Success")
HyperLink1.NavigateUrl = "Url to Smiley";
else
HyperLink1.NavigateUrl = "Url to Frowney";
}
}
HyperLink HyperLink1 = (HyperLink)e.Row.FindControl("HyperLink1");
switch (HyperLink1.Text)
{
case "Completed":
HyperLink1.ImageUrl = "Images\\Success.png";
HyperLink1.ToolTip = "Completed";
etc
The ToolTip property maps to the alternate text for the image.
Thanks to codingbiz for getting me started.
If you are trying to set the ImageUrl property I suggest using the RowDataBound event. The handler method could would look something like:
protected void questionsGridView_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
DataSourceDataType row;
HyperLink hyperLink1;
if (e.Row.RowType == DataControlRowType.DataRow & e.Row.DataItem is DataSourceDataType)
{
row = (DataSourceDataType)e.Row.DataItem;
hyperLink1 = (HyperLink)e.Row.FindControl("HyperLink1");
hyperLink1.ImageUrl = (row.IsSuccess) ? "~/images/success.png" : "~/images/failure.png";
}
}
Another trick I have used is altering the data object you are binding to to have a property which indicates the URL to use:
partial class DataSourceDataType
{
public string SuccessImgURL
{
get
{
return (IsSuccess) ? "~/images/success.png" : "~/images/failure.png";
}
}
}
Then you bind to that property.
Note: IsSuccess would need to be replaced with your own field name or boolean condition.
I often use this with LINQ to SQL objects, so adding properties can be done in a separate file using partial classes. This way you do not have to worry about the LINQ to SQL tools removing your additions.

data replacing in gridview

I am working in ASP.Net, I am saving the status field in Database as true or false. Now, I want to display the true or false as Active or Inactive in the front end in GridView. How to display the data in Gridview.
Thanks in advance.
The alternative is to use your datagrid's RowDataBound event to convert what is it to the strings active / inactive:
Protected Sub gvRequests_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvRequests.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lbl As Label = CType(e.Row.FindControl("lblStatus"), Label)
If lbl.Text="1" then
lbl.Text="Active"
else
lbl.Text="Inactive"
end if
end if
end sub
If you're asking how to change true and false to Active and Inactive, you could use a CASE statement in your SQL query, like this:
SELECT CASE Status WHEN 1 THEN 'Active' WHEN 0 THEN 'Inactive' END FROM Something
For a more specific answer, please post more details.
use checkbox column to show the status field. ( set that column to disable )
If you know the cell location of which you want to filter data, you could also do this in the gridviews RowDataBound event.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[2].Text == "1")
e.Row.Cells[2].Text = "True";
else
e.Row.Cells[2].Text = "False";
}
}
This is what I used to find and replace text in a gridview.
If you are using template field then you can create server side function and call on Eval like below
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblstatus" runat="server" Text='<%# GetStatusText(Eval("status")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
public string GetStatusText(string strIsActive)
{
bool val = Boolean.Parse(strIsActive);
if(val)
{
return "Active";
}
else
{
return "Inactive";
}
}

How can I access DataGridRow from a textbox on that row?

In a DataGrid, when text in a textbox changes I want to add the value of another field in that row to an array.
public void txtTitle_TextChanged(object sender, EventArgs e)
{
TextBox titleBox = (TextBox)sender;
DataGridItem myItem = (DataGridItem)titleBox.Parent.Parent;
string test = DataBinder.Eval(myItem.DataItem, "prod_id").ToString();
}
However myItem.DataItem evaluates as null. I was expecting it to evaluate as DataRowView?
You can get the TextChanged event to fire if you do the following:
<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="False"
onitemdatabound="DataGrid1_ItemDataBound">
<Columns>
<asp:TemplateColumn HeaderText="Test">
<ItemTemplate>
<asp:TextBox OnTextChanged="txtBox_TextChanged" ID="TextBox1" runat="server" AutoPostBack="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="Name" HeaderText="Test 1"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
You will notice that i have the following properties set:
AutoPostBack="True"
I have also manually added the OnTextChanged="txtBox_TextChanged" to the text box as well.
In my code behind i have:
protected void txtBox_TextChanged(object sender, EventArgs e)
{
TextBox txtBox = (TextBox)sender;
Label1.Text = txtBox.Text;
}
The only way the event will fire is when you lose focus on the text box after typing.
Key points to consider:
This will cause a post back, so Ajax might be a good way to keep the user experience nice.
You will need to make sure you wrap your DataBind() in a if (!IsPostBack)
Hope this helps!
Effectively, I solved this by adding an autonumber column to the table, and using the value of this to determine the row's positino in the table, then using the value of this to affect the appropriate row in the datagrid.
I'm now merely changing the color of the row rather than adding values in that row to an array, as stated in the original question.
public void txtPrice_TextChanged(object sender, EventArgs e)
{
TextBox txtPrice = (TextBox)sender;
DataGridItem myItem = (DataGridItem)txtPrice.Parent.Parent;
markRows(myItem, true);
}
public void markRows(DataGridItem myItem, bool toSave)
{
// Prepeare to save this record?
CheckBox thisSave = (CheckBox)myItem.FindControl("chkSave");
thisSave.Checked = toSave;
// Establish the row's position in the table
Label sNo = (Label)myItem.FindControl("SNo");
int rowNum = Convert.ToInt32(sNo.Text) - 1;
CheckBox rowSave = (CheckBox)grid.Items[rowNum].FindControl("chkSave");
// Update background color on the row to remove/add highlight
if (rowSave.Checked == true)
grid.Items[rowNum].BackColor = System.Drawing.Color.GreenYellow;
else
{
Color bgBlue = Color.FromArgb(212, 231, 247);
grid.Items[rowNum].BackColor = bgBlue;
// some code here to refresh data from table?
}
}

Categories