Using Sql data after binding to repeater - c#

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

Related

how to change row color in dev express grid after the data is loaded from the database in c# winforms

i am newbie to dev express.
i want to change the row background color in dev express grid after the data is loaded in C# winforms.
i am populating the data grid from the below code
string sReportSql = "SELECT * FROM Employee";
private void Form_Load(object sender, EventArgs e)
{
dataGridView.DataSource = GeDataFromDb();
}
private DataTable GeDataFromDb()
{
DataTable dtGenericReport = new DataTable();
using (SqlConnection con = new SqlConnection(connString))
{
if (sReportSql != null)
{
using (SqlCommand cmd = new SqlCommand(sReportSql, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtGenericReport.Load(reader);
}
}
}
return dtGenericReport;
}
i tried using the Row Style event but it does not seems to be working
private void gridview1_RowStyle(object sender, RowStyleEventArgs e)
{
GridView View = sender as GridView;
if (e.RowHandle >= 0) {
string status = View.GetRowCellDisplayText(e.RowHandle, View.Columns["status"]);
if (status == "Completed") {
e.Appearance.BackColor = Color.IndianRed;
}
}
}
The best way that I know is to use CustomDrawCell event. Something like the following code.
private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
GridView View = sender as GridView;
if (e.RowHandle >= 0) {
string status = View.GetRowCellDisplayText(e.RowHandle, View.Columns["status"]);
if (status == "Completed") {
e.Appearance.BackColor = Color.IndianRed;
}
}
}
It seems to me that there is no problem in your code
I think the name of event gridview1_RowStyle should be gridview_RowStyle
you may have made a mistake by selecting another gridview
you can check it in Run designer

Formatting Cells on Gridview from SQL Data Reader

I have a Grid view which populates through my SQL data reader
Grid View:
<asp:GridView ID="gridviewALL" runat="server" OnItemDataBound="Search_ItemDataBound">
</asp:GridView>
SQL Data Reader:
SqlCommand cmd = new SqlCommand("SELECT en.dpCreatedDT AS 'Time Received', en.enStatusCH AS 'Status', en.enNotificationNoNI AS 'LSBUD Ref', cm.cmpersonfirstch AS 'First Name', cm.cmPersonLastCH AS 'Last Name', cm.cmcompanynamech AS 'Company' FROM dp_enquiry en JOIN dp_caller_master cm ON (en.encmcallerkeyfk = cm.cmCallerKeyNI) WHERE en.ennotificationnoni = #JobnoALL", conn);
try
{
SqlParameter search = new SqlParameter();
search.ParameterName = "#JobnoALL";
search.Value = JobnoALL.Text.Trim();
cmd.Parameters.Add(search);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
gridviewALL.DataSource = dt;
gridviewALL.DataBind();
}
I'm trying to change the format of a cell in the grid view when the text equals a value, I've done this using a listview before but the Gridview steps seems different. I have the following which doesn't seem to be working any suggestions?
private void Search_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
string CurrentColumn = e.Item.Cells[1].Text;
if (CurrentColumn == "PROC")
{
e.Item.Cells[1].Text = "Creating PDF";
}
else if (CurrentColumn == "CLOS")
{
e.Item.Cells[1].Text = "Complete";
e.Item.Cells[1].ForeColor = System.Drawing.Color.Green;
}
}
It must be reading the header, you need to check if its a DataRow:-
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CurrentColumn = e.Item.Cells[1].Text;
//your code goes here..
}
Also, I would suggest you to use DataBinder.Eval method instead to avoid hard-coding of cell index as it may result in error if order of columns change.
string CurrentColumn = DataBinder.Eval(e.Row.DataItem, "yourColumnName").ToString();
Update:
Just noticied you are using ItemDataBound which is an event for DataGrid and not Gridview. Use RowDataBound event instead:-
<asp:GridView ID="gridviewALL" runat="server" OnRowDataBound="gridviewALL_RowDataBound">
</asp:GridView>
Your rowDataBound event should look like this:-
protected void gridviewALL_RowDataBound(object sender, GridViewRowEventArgs e)
{
//your code here
}

Stop updatting DetailsView based on IF condition

I have DetailsView with connected SqlDataSource and I want cancel updating row when my condition is true in OnRowUpdating event
I did this step but when condition is true DetailsView still at editing mode all I need to return to normal view if the condition is true
protected void DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
// Iterates through the rows of the GridView control
foreach (DetailsViewRow row in DetailsView1.Rows)
{
// Selects the text from the TextBox
// which is inside the GridView control
// Selects the text from the DropDownList
// which is inside the GridView control
string dropDownListText = ((DropDownList)
row.FindControl("DropDownList12")).SelectedItem.Text;
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd2 = new SqlCommand();
conn.Open();
cmd2.CommandText = #"Select StatusID from ComplainMain Where TicketID=#tktid";
cmd2.Parameters.AddWithValue("#tktid", ticketid.tktid);
cmd2.Connection = conn;
SqlDataReader rdr = cmd2.ExecuteReader();
int status;
while (rdr.Read())
{
status = rdr.GetInt32(0);
if (status == 3)
{
Label18.Visible = true;
Label18.Text = "Can not Modify this Complaint as Ticket Closed refer to the Admin";
e.Cancel = true;
}
}
}
}
Page_Load
protected void Page_Load(object sender, EventArgs e)
{
Label18.Visible = false;
DetailsView1.ItemUpdating += new DetailsViewUpdateEventHandler(DetailsView1_ItemUpdating);
}
Use ChangeMode method on your DetailsView
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);

asp.net repeater for each row

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

Load Databind DropDownList inside ListView

I have a ListView control that contains a DropDownList control inside the ItemTemplate tag.
I am trying to load the existing list items to the DropDownList using the codes below inside the ItemCommand event of the ListView control:
DropDownList ddlItem = (DropDownList)e.Item.FindControl("ddlItem");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ID, Name FROM Items";
SqlDataReader data = cmd.ExecuteReader();
ddlItem.DataSouce = data;
ddlItem.DataTextField = "Name";
ddlItem.DataValueField = "ID";
ddlItem.DataBind();
con.Close();
After binding the items, I want to choose the selected items based from the database records.
Am I missing something?
You should do that in the ListView's ItemDataBound event instead. You will find your DropDownList there via e.Item.FindControl("ddlItem") get the underlying datasource for that item via e.Item.DataItem. Use the debugger if you're unsure about the types.
protected void ListView1_ItemDataBound(Object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
DropDownList ddlItem = (DropDownList) e.Item.FindControl("ddlItem");
var rowView = e.Item.DataItem as DataRowView;
int id = (int)rowView["ID"]; // whatever
// get data from id ...
//ddlItem.DataSouce = data;
//ddlItem.DataTextField = "Name";
//ddlItem.DataValueField = "ID";
//ddlItem.DataBind();
}
}

Categories

Resources