I have a repeater that retrieve data from my db.
some of the results are getting a null value in a specific column due to
a join query and its fine.
I would like to go over each row and if the result is null for the specific
row i want to change the css for this row.
Now for the code:
<asp:Repeater ID="repRequests" OnItemDataBound="repRequests_ItemDataBound" runat="server">
<ItemTemplate>
<asp:Label ID="lbltest" runat="server" Text='<%#Eval("val_name") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
C#:
if (!IsPostBack)
{
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("check_accepted", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#val_name", Session["valName"].ToString());
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
repRequests.DataSource = dr;
repRequests.DataBind();
}
}
How to write this ?
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
**//what i want to get:**
if (dr["accepted_id"] == Null) // a column from the db table
{
repRequests.attribute["class"] = "Some Class"
}
}
}
Thanks for the helpers !
You can try the following. If the data source is a DataReader object, you must cast e.Item.DataItem as type DBDataRecord (from System.Data.Common)
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Data.Common.DbDataRecord dataRow = e.Item.DataItem as System.Data.Common.DbDataRecord;
if (dataRow["accepted_id"] == DBNull.Value || dataRow["accepted_id"] == null) // a column from the db table
{
// I am not sure how to you get repRequests. but you can find the control using e.Row.Item.FindControl() function
repRequests.attribute["class"] = "Some Class";
}
}
}
EDIT
Further to your questions, if you want to change the css of a perticular row, if some value is null, you cannot set css to repeater or repeater item directly. What you need to do is add a top level panel to the ItemTemplate like this
<ItemTemplate>
<asp:Panel runat="server" ID="panelRow">
<asp:Label ID="lbltest" runat="server" Text='<%#Eval("val_name") %>'></asp:Label>
</asp:Panel>
</ItemTemplate>
Then you can change the css of the panel like below
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Data.Common.DbDataRecord dataRow = e.Item.DataItem as System.Data.Common.DbDataRecord;
if (dataRow["accepted_id"] == DBNull.Value || dataRow["accepted_id"] == null) // a column from the db table
{
Panel panelRow = e.Item.FindControl("panelRow") as Panel;
panelRow.CssClass = "yourcssclass";
}
}
}
If not, you can use IsNull in your query.
SqlCommand cmd = new SqlCommand("select IsNull(something,zero) from sometable",connectionstring)
SqlDatareader dr = cmd.ExecuteReader();
while(dr.Read())
{
if(dr.GetString(0)=="zero")
{
repRequests.attribute["class"] = "Some Class";
}
}
Here is link example of DbDataRecord when you bind repeater control with sqldatareader.
Also note that repRequests.attribute["class"] = "Some Class" this means you are applying CSS Class to the repeater control. You need to change the CssClass label which is used as item of repeater control.
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
DbDataRecord dbr = (DbDataRecord)e.Item.DataItem;
if( Convert.ToString(DataBinder.Eval(dbr, "accepted_id")) == null )
((Label)e.Item.FindControl("lbltest")).CssClass = "Some Class";
}
}
Related
I need to format 2 entire columns in my gridview based on if the cell contains the string "yes" or "no". I've looked everywhere trying to find something accomplishing what I'm trying to do and cant find anything based on a string, only int values.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gv = (GridView)e.Row.FindControl("GridView2");
var ds = new SqlDataSource();
ds.ConnectionString = ConfigurationManager.ConnectionStrings["HUTDMSConnectionString"].ConnectionString;
ds.SelectCommand = "SELECT * FROM textBooks WHERE CourseID = '" + GridView1.DataKeys[e.Row.RowIndex].Value + "' ORDER BY BookTitle";
gv.DataSource = ds;
gv.DataBind();
}
}
I know that the conditional formatting goes within the gridview_rowdatabound
event.
What I have so far:
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow && ((e.Row.RowState & DataControlRowState.Edit) == 0))
{
var valueFetched = ((TableCell)(e.Row.Cells[3].FindControl("no"))).Text;
if (valueFetched == "no")
{
foreach (var cell in e.Row.Cells)
((TableCell)cell).BackColor = Color.Red;
}
}
}
Look at this example to get some direction. This code goes under RowDataBound
if (e.Row.RowType == DataControlRowType.DataRow && ((e.Row.RowState & DataControlRowState.Edit) == 0))
{
var valueFetched = ((Label)(e.Row.Cells[1].FindControl("yourControlId"))).Text;
if (valueFetched == "1")
{
foreach (var cell in e.Row.Cells)
((TableCell)cell).BackColor = System.Drawing.Color.LightBlue;
}
}
I'm trying to do a project for car maintenance, and I have a small problem. The project is something like:
4 kind of maintenance plans for different cars.
CarA ( MirrorA, etc etc )
CarB ( MirrorB, etc etc )
CarC ( MirrorC, etc etc )
CarD ( MirrorD, etc etc )
What I'm trying to do is when I chose a Car (from a DropDownList), the program selects the right maintenance plan for the car!
SqlCommand cmd = new SqlCommand("Select id, description from accauto_maps", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "description";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
Now I'm stuck.
now you need to set SelectedValue in this list
and/or
define event OnSelectedIndexChanged where you will process user's selection
Below the example how we did it:
<asp:DropDownList ID="ddlStatus" AutoPostBack="True" runat="server" DataSourceID="EDSLookStatus"
DataValueField="cd"
DataTextField="lookupName"
OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged" />
<asp:TextBox ID="txtBxStatus" runat="server" Text='<%# Bind("status") %>' Visible="False" />
Here is the trick: added invisible textbox, which is linked to "status". When ddl change value it set new value to this txtBx:
protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = FormViewClient.FindControl("ddlStatus") as DropDownList;
TextBox txtBx = FormViewClient.FindControl("txtBxStatus") as TextBox;
if (ddl != null && txtBx != null)
{ txtBx.Text = ddl.SelectedValue; }
}
to set selected value:
<asp:FormView ... OnDataBound="FormViewClient_DataBound" >
and
protected void FormViewClient_DataBound(object sender, EventArgs e)
{
...
DropDownList ddl = FormViewClient.FindControl("ddlStatus") as DropDownList;
TextBox txtBx = FormViewClient.FindControl("txtBxStatus") as TextBox;
if (ddl != null && txtBx != null)
{ ddl.SelectedValue = txtBx.Text; }
...
}
I could not properly bind my child repeater (lvTwo) using a datatable. It always throws a NullReferenceException. On debug mode, my datatable looked fine, any thoughts?
HTML Code:
<asp:Repeater ID="lvOne" runat="server" OnItemDataBound="lvOne_ItemDataBound">
<ItemTemplate>
<div>
I am the one.
</div>
<asp:Repeater ID="lvTwo" runat="server">
<ItemTemplate>
I am the two.
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
Code-behind (dtTable to bind for lvOne, dtTable2 to bind for lvTwo):
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtTable = new DataTable();
dtTable.TableName = "T1";
dtTable.Columns.Add("ProjectName");
DataRow dr = dtTable.NewRow();
dr["ProjectName"] = "ThreeSixFive";
dtTable.Rows.Add(dr);
if (!Page.IsPostBack)
{
lvOne.DataSource = dtTable;
lvOne.DataBind();
}
}
protected void lvOne_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
DataTable dtTable2 = new DataTable();
dtTable2.TableName = "T2";
dtTable2.Columns.Add("C");
DataRow dr = dtTable2.NewRow();
dr["C"] = "ThreeSixFive";
dtTable2.Rows.Add(dr);
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (dtTable2 != null)
{
lvTwo.DataSource = dtTable2;
lvTwo.DataBind();
}
}
}`
The culprit was due to the unrecognized lvTwo control. It was able to compile due to the control being registered in the designer file, instead I need to use the ff:
var lvTwo = (ListView) e.Item.FindControl("lvTwo");
Good day, I want the text of the button inside the repeater to change dynamically based on what the sql selected values would have.
here's my code:
asp.cs
if (!IsPostBack)
{
string getEmp = "Select employeeid, photo, lastname, firstname, departmentname, designation,userType from tblEmployee e inner join tblDepartment d on d.departmentid=e.department";
SqlCommand com = new SqlCommand(getEmp,con);
con.Open();
SqlDataReader dr = com.ExecuteReader();
Button btnSet = (Button)FindControl("btnSet");
if (dr.HasRows)
{
if (dr.Read())
{
if (btnSet != null)
{
if (dr["userType"].ToString() == "2")
{
btnSet.Text = "Set as Normal User";
}
else
{
btnSet.Text = "Set as Power User";
}
}
}
}
Repeater1.DataSource = dr;
Repeater1.DataBind();
dr.Dispose();
con.Close();
aspx
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<asp:Button ID="btnSet" commandname="set" commandargument=<%# Eval ("employeeid") %> runat="server" class="tiny success expand button" Text="" />
You can subscribe to the Repeater's ItemDatabound event. It allows you to access the controls of the item and change them based on the values of the current item:
private void Repeater1_ItemDatabound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// Retrieve button of the line
var btn = e.Item.FindControl("btnSet") as Button;
if (btn != null)
{
// Set text of button based on e.Item.DataItem;
}
}
}
try this its too much short and working
<asp:Button ID="btnSet" commandname="set" commandargument=<%# Eval("employeeid") %> runat="server" class="tiny success expand button" Text='<%# Eval("userType").ToString() == "2" ?"Set as Normal User" : "Set as Power User" %>' />
let me know if you need any more help
You have to use the databind event of your repeater.
Something like:
void Repeater1_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
// Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
Button btnSet = (Button)e.Item.FindControl("btnSet");
if ( e.Item.DataItem["userType"].ToString() == "2")
{
btnSet.Text = "Set as Normal User";
}
else
{
btnSet.Text = "Set as Power User";
}
}
}
I wish to use some data from the database after binding my query to a repeater. But i'm not sure how i am supposted to do this. Here is my code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT * FROM kontakt", conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
Repeater_Beskeder.DataSource = reader;
Repeater_Beskeder.DataBind();
foreach (RepeaterItem row in Repeater_Beskeder.Items)
{
if (reader.Read())
{
Panel Vis_Panel = (Panel)row.FindControl("Panel_Vis_Besked");
if (Request.QueryString["id"].ToString() == reader["id"])
{
Vis_Panel.Visible = true;
}
}
}
conn.Close();
My reader wont work as it's allready been binded to my repeater, so i'm quite lost.
I hope some of you have another solution to this problem.
ItemDataBound Event Occurs after an item in the Repeater control is data-bound but before it is rendered on the page.
void Repeater_Beskeder_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
// This event is raised for the header, the footer, separators, and items.
// Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
Panel Vis_Panel = (Panel)row.FindControl("Panel_Vis_Besked");
if (Request.QueryString["id"].ToString() == reader["id"])
{
Vis_Panel.Visible = true;
}
}
}