Remove ddl's that has no value's - c#

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;
}
}
}

Related

How to mark records in gridview as read and unread

This is my GridView1. I want the latest record to be highlighted and after user click the authorization no(which user viewed the record in next page), the row will not be highlighted (means after the user view the record, the row is back to normal, no highlight no bold font).
My current progress is,
I have created new bit field in my database named ReadStatus, and defaulted to 0
Next, I need to do the onrowdatabound coding in order to implement this.
first question is, do i need to read the bit column(ReadStatus) as I read all this column?AuthorizationNo, ProductID,Name,Qty,---(ReadStatus)??
should I read ReadStatus in this code?
/ /READING RECORD FROM TABLE TRACK_ITEM
while (reader.Read())
{
MerchantProduct merchantProduct = new MerchantProduct();
merchantProduct.TxID = reader["TxID"].ToString();
merchantProduct.ProductID = reader["ProductID"].ToString();
merchantProduct.Name = reader["ProductName"].ToString();
merchantProduct.Qty = Convert.ToInt32(reader["Qty"]);
listLatestProduct.Add(merchantProduct);
}
return listLatestProduct;
second is, can anyone show me the proper way to code in onrowdatabound?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Tried many code here but none is working
}
Thank you.
First you need to add one more column in ur db for ReadStatus(1/0),
then make is as hiddenfield in your aspx page.
<asp:TemplateField HeaderText="ReadStatus" Visible="false">
<ItemTemplate>
<asp:Label ID="readStatus" runat="server"></asp:Label>
<asp:HiddenField ID="readStatusHiddenField" runat="server" Value='<%#Eval("ReadStatus") %>'/>
</ItemTemplate>
</asp:TemplateField>
In your grid rowdataboun, just paste this code.It works for me
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// searching through the rows
if (e.Row.RowType == DataControlRowType.DataRow)
{
int reading = Convert.ToInt32(((HiddenField)e.Row.FindControl("readStatusHiddenField")).Value);
if (reading == 0)
{
e.Row.BackColor = Color.LightGray;
e.Row.Font.Bold = true;
}
}
}

Manipulate SQL values before displaying on GridView

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!

How to change column values to show different value in bind DataGridView?

I have a dataGridView, which is data bound to some generic List<T> (while T is some custom class with properties).
The problem is that one of the property is type of integer, and it represents minutes.
After binding List to dataGridView, I want that column shows hours, instead of minutes by default.
How to change some column`s behaviour, to use some math over it to show a bit different values?
Do I have to do this in the DataGridView.CellFormating event?
You have two options, the first one is to manipulate your Generic List<T> first, that should be faster than using the second option, iterating through your list on each RowDataBound Event.
Using RowDataBound Event
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int minutes = int.Parse(e.Row.Cells[YourColumnIndex].Text);
decimal hours = minutes / 60;
e.Row.Cells[YourColumnIndex].Text = hours.ToString();
}
}
Using Evel Expression
ASPX Page
<asp:TemplateField HeaderText="Time">
<ItemTemplate>
<%# ConvertToHours(Eval("Minutes"))%>
</ItemTemplate>
</asp:TemplateField>
Code Behind
private string ConvertToHours(object objMin)
{
if (Convert.ToInt32(objMin) == 1)
{
return (int.Parse(objMin) / 60).ToString();
}
else
{
return "0";
}
}
Another approach. - do-it-all in single shot.
<asp:TemplateField HeaderText="Time">
<ItemTemplate>
<asp:Label ID="lblTime" runat="server" Text='<%# Convert.ToInt32(Eval("Time")) Convert.ToInt32("60")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Update: As the Question updated, Then for Windows Forms application you should use DataGridView.CellFormatting Event
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// If the column is the Time column, check the
// value.
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Time")
{
if (e.Value != null)
{
//Your implementation.
}
}
}

How to disable a control in command field control in gridview

how to find a command field control in the gridview.
in a method not in the row data bound.
so far i have used this coding but i cant find the control.
<asp:CommandField ButtonType="Image" ShowEditButton="True
HeaderText="Enter Leave"
EditImageUrl="~/IMAGES/edit-icon.gif">
<ItemStyle HorizontalAlign="Center" />
</asp:CommandField>
source code:
ImageButton edit = (ImageButton)EmployeeDetails.FindControl("Image");
edit.Enabled = false;
You can disable column itself with,
GridView1.AutoGenerateEditButton = false;
from code behind pages.
Or you can use ItemTemplate instead of CommandField,
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="id" CommandName="Edit" Text="Edit" />
</ItemTemplate>
</asp:TemplateField>
And at code behind you can iterate through rows of GridView and disable each LinkButton.
foreach(GridViewRow gvr in GridView1.Rows)
{
LinkButton row = gvr.FindControl("id") as LinkButton;
row.Enabled = false;
}
First Edit :
I tried my second solution and it works. However, make sure your GridView is filled before you use foreach. Otherwise, GridView.Rows.Count would probably be 0.
Second Edit :
This works for CommandField too. Replace 0 with the location of CommandField in your GridView.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Enabled = false;
}
}
You miss to specify the row
Something like :
ImageButton edit = (ImageButton)EmployeeDetails.Rows[0].Cells[0].FindControl("Image");
edit.Enabled = false;
If you want to disable the column that contains the imageButton , you can do :
EmployeeDetails.Columns[0].Visible = false;
Try this:
try to hide controls at DataBound or RowDataBound event of GridView
protected void EmployeeDetails_DataBound(object sender, EventArgs e)
{
ImageButton edit = (ImageButton)EmployeeDetails.Row.Cells[0].FindControl("Image");
edit.Visible = false;
edit.Enabled = false; //OR use this line
}
particular column can be disabled in the following way
EmployeeDetails.Columns[0].Visible = false;
Hope this helps.
I had a similar issue. I simply disabled the view of the Column in BindData() function.
GridView1.Columns[0].Visible = false;
This worked for me, since my first column was Edit column and I have to enable it for specific users only.
Good luck!
Cast it as a DataControlFieldCell and then set Enabled to false.
Where: row.Controls[0] is your CommandField control
foreach (GridViewRow row in ManageDNXGridView.Rows)
{
DataControlFieldCell editable = (DataControlFieldCell)row.Controls[0];
editable.Enabled = false;
}

Getting total for a column in ListView

I need to get a sum for all items in a column within a listview. I put in the following code in the itemdatabound event, but realized after testing it that it will only be getting what is bound, oops.
So I was looking for a little help converting this to show a total for my column from all items bound to the ListView.
Thanks.
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem item = (ListViewDataItem)e.Item;
Label lblQty = (Label)e.Item.FindControl("lblQuantity");
if (lblQty == null)
{
return;
}
if (lblQty.Text.Length == 0 || lblQty.Text == "")
{
return;
}
else
{
ListViewTotal += int.Parse(lblQty.Text);
}
}
The best method I have found to do this is to implement the OnDataBinding method for the control you are binding. For example:
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<asp:Literal ID="yourLiteral" runat="server"
OnDataBinding="yourLiteral_DataBinding"></asp:Literal>
</ItemTemplate>
</asp:ListView>
First define a global counter in your .cs:
private int _quantityTotal = 0;
Then implement the OnDataBinding for the control:
protected void yourLiteral_DataBinding(object sender, System.EventArgs e)
{
// You could get anything here to get a value including calling a DB
// call if you want for each item that is being bound.
Literal lt = (Literal)(sender);
int quantity = (int)(Eval("yourQuantityField"));
_quantityTotal += quantity;
lt.Text = quantity.ToString();
}
Now you have the total stored in _quantityTotal which you can then add to a footer or something else after the databinding has occurred like the OnDataBound event.
Yes, you will have to query the DB to get this value, or depending on what you are binding, loop through the collection you are binding and sum the values from the classes or DataSet/DataTable you are binding to it.
HTH.

Categories