I don't normally work with OnRowDataBound, but I need to in this case because I need to change the back color of rows based on a specific field.
Here's my ASPX:
<div id="divGrid" style='width:920px; height:430px; overflow:auto'>
<asp:DataGrid ID="DataGrid_AuditSearch" runat="server"
AllowPaging="True" AllowSorting="True" CellPadding="4" ForeColor="#333333"
GridLines="None" AutoGenerateColumns="False"
OnRowDataBound="DataGrid_AuditSearch_RowDataBound"
OnCancelCommand="DataGrid_AuditSearch_CancelCommand"
OnUpdateCommand="DataGrid_AuditSearch_UpdateCommand"
OnEditCommand="DataGrid_AuditSearch_EditCommand">
<AlternatingItemStyle Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<EditItemStyle BackColor="#999999" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<PagerStyle BackColor="#5D7B9D" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Width="920px" Font-Underline="False" />
<SelectedItemStyle BackColor="#E2DED6" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<Columns>
<asp:EditCommandColumn ButtonType="PushButton" CancelText="Cancel"
EditText="Select" UpdateText="Update"></asp:EditCommandColumn>
<asp:BoundColumn DataField="AUDIT_ID" HeaderText="Audit ID"/>
<asp:BoundColumn DataField="PLAN_ID" HeaderText="Plan ID"/>
<asp:BoundColumn DataField="PLAN_DESC" HeaderText="Plan Desc"/>
<asp:BoundColumn DataField="DOC_TYPE" HeaderText="Doc Type"/>
<asp:BoundColumn DataField="PRODUCT" HeaderText="Product"/>
<asp:BoundColumn DataField="PLAN_TYPE" HeaderText="Plan Type"/>
<asp:BoundColumn DataField="Auditor_ID" HeaderText="Auditor ID"/>
</Columns>
</asp:DataGrid>
<asp:Label ID="lblEmpty" runat="server" Visible="false" Style="font-weight:bold; font-size:large;"></asp:Label>
</div>
and here's my C# Code-Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Sometimes you need the parameter, sometimes you don't. This works for both cases.
txtAuditSearch.Text = (Request["AuditID"] ?? String.Empty).ToString();
Show_Data(0);
}
else
{
}
}
public void Show_Data(int AuditID)
{
OracleConnection conn = GetConnection();
try
{
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnCST"].ToString();
OracleCommand cmd3 = new OracleCommand();
cmd3.Connection = conn;
string sqlquery2;
//sqlquery2 = "SELECT * FROM F_Audit_Plan Where Audit_ID = " + AuditID + "";
sqlquery2 = "SELECT FAP.AUDIT_ID, FAP.PLAN_ID, FAP.PLAN_DESC, DTY.DOC_TY AS DOC_TYPE, DP.PRODUCT, ";
sqlquery2 = sqlquery2 + "DPT.PLAN_TYPE, FA.Auditor_Lan_ID AS Auditor_ID, FAP.Plan_Review_Ind ";
sqlquery2 = sqlquery2 + "FROM F_Audit_Plan FAP ";
sqlquery2 = sqlquery2 + "LEFT JOIN D_DOC_TY DTY ";
sqlquery2 = sqlquery2 + "ON FAP.DOC_TY_ID = DTY.DOC_TY_ID ";
sqlquery2 = sqlquery2 + "LEFT JOIN D_PRODUCT DP ";
sqlquery2 = sqlquery2 + "ON FAP.PRODUCT_ID = DP.PRODUCT_ID ";
sqlquery2 = sqlquery2 + "LEFT JOIN D_PLAN_TYPE DPT ";
sqlquery2 = sqlquery2 + "ON FAP.PLAN_TY_ID = DPT.PLAN_TY_ID ";
sqlquery2 = sqlquery2 + "LEFT JOIN F_Audit FA ";
sqlquery2 = sqlquery2 + "ON FA.Audit_ID = FAP.Audit_ID ";
sqlquery2 = sqlquery2 + "Where FAP.Audit_ID = " + AuditID + " ";
sqlquery2 = sqlquery2 + "ORDER BY FAP.PLAN_DESC ASC ";
cmd3.CommandText = sqlquery2;
var SearchAdapter = new OracleDataAdapter(cmd3);
var ds = new DataSet();
SearchAdapter.Fill(ds);
// Perform the binding.
DataGrid_AuditSearch.DataSource = ds;
DataGrid_AuditSearch.DataBind();
if (DataGrid_AuditSearch.Items.Count < 1)
{
lblEmpty.Visible = true;
lblEmpty.Text = "There is no data to display";
}
else
{
lblEmpty.Visible = false;
}
conn.Close();
//DataGrid_AuditSearch.Columns[3].Visible = false;
//DataGrid_AuditSearch.Columns[1].Visible = false;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
conn.Close();
}
}
protected void DataGrid_AuditSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Status = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Plan_Review_Ind"));
if (Status == "Y")
{
e.Row.Attributes["style"] = "background-color: #28b779";
}
else
{
e.Row.Attributes["style"] = "background-color: #da5554";
}
}
}
I put a break point on the first line in the DataGrid_AuditSearch_RowDataBound function and it never even hits it. Any idea what I'm doing wrong?
Check this guy out, looks like setting AutoGenerateColumns="False" breaks this some.
You are using a DataGrid, not a GridView. The DataGrid does not have an OnRowDataBound event. Use the OnItemDataBound event instead.
Read more about it at Microsoft.
Related
Here is my case.
I've saved data from CheckBoxList:
foreach (ListItem li in CheckBoxList1.Items)
{
Steps = String.Join(", ", CheckBoxList1.Items.Cast<ListItem>()
.Where(i => i.Selected));
}
It works fine but what I want is to get back this data from database in checkBoxList inside a DataGrid.
And bellow are many things I tried. Please help:
<div align="center" style="margin-top: 50px;">
<asp:GridView ID="GridView1" runat="server" BackColor="White" DataKeyNames="SNo"
OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="False"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing"
BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Vertical" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="TransactionName" HeaderText="Transaction Name" />
<asp:BoundField DataField="Category" HeaderText="Category" />
<asp:TemplateField HeaderText="Steps">
<ItemTemplate>
<asp:Label ID="lblBrand" runat="server" Text='<%#Eval("Steps") %>'>
</asp:Label>
<asp:CheckBoxList ID="CheckBoxList2" runat="server">
</asp:CheckBoxList>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<EditRowStyle Height="10px" Width="2px" />
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
The C# code behind
private void Bind_CheckBoxList()
{
DataTable dt;
String SQL = "SELECT * from TransactionDetail";
string sConstr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr))
{
using (SqlCommand comm = new SqlCommand(SQL, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt = new DataTable("tbl");
da.Fill(dt);
}
conn.Close();
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBoxList c = (CheckBoxList)e.Row.FindControl("CheckBoxList2");
DataTable dt;
String SQL = "SELECT * FROM TransactionDetail";
string sConstr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr))
{
using (SqlCommand comm = new SqlCommand(SQL, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
if (c != null)
{
Label test = (Label)(e.Row.FindControl("lblBrand"));
Steps = test.Text;
string[] items = Steps.Split(new[] { ", " }, StringSplitOptions.None);
foreach (ListItem li in c.Items)
li.Selected = items.Contains(li.Text);
}
dt = new DataTable("tbl");
da.Fill(dt);
}
}
c.DataSource = dt;
c.DataTextField = what to write here to pass the array Text;
c.DataValueField = "SNo";
c.DataBind();
}
}
Hey thanks i solve it by creating another table for Steps and same for Documents Required ,,, its now showing the checkBoxList that i want into the datagrid and bellow the Code
if ((e.Row.RowState & DataControlRowState.Edit) == 0)
{
CheckBoxList c = (CheckBoxList)e.Row.FindControl("CheckBoxList2");
CheckBoxList CheckBoxListDR = (CheckBoxList)e.Row.FindControl("CheckBoxList3");
DataTable dt;
String SQL = "SELECT distinct S.Steps, D.DocumentsRequired, T.TransactionID FROM [StepsIsSelectedTable] S JOIN TransactionDetail T " +
" ON S.TransactionIDSteps = T.TransactionID JOIN DocumentsRequiredIsSelected D " +
"ON D.TransactionIDDR = T.TransactionID WHERE " +
"TransactionIDDR ='" + TreeView1.SelectedValue + "' and S.StepsIsSelected='True' and D.DocumentsRequiredIsSelected='True'" +
" group by S.Steps, D.DocumentsRequired ,T.TransactionID";
string sConstr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr))
{
using (SqlCommand comm = new SqlCommand(SQL, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt = new DataTable("tbl");
da.Fill(dt);
}
}
c.DataSource = dt;
CheckBoxListDR.DataSource = dt;
c.DataTextField = "Steps";
c.DataValueField = "TransactionID";
CheckBoxListDR.DataTextField = "DocumentsRequired";
CheckBoxListDR.DataValueField = "TransactionID";
c.DataBind();
c.SelectedValue = "TransactionID";
CheckBoxListDR.DataBind();
CheckBoxListDR.SelectedValue = "1";
}
}
I want to pass the query string value without redirecting to current page I have tried these code but I can even see the query string value variable to pass in these page.I have attached my code below.help me out from these problem
Thanks in advance
Aspx design code
<div class="col span_1_of_1">
<asp:GridView ID="gridweeks" runat="server" CssClass="grid" ShowHeaderWhenEmpty="True" ShowFooter="true" Style="width: 40%" AllowPaging="true" PageIndex="0" PageSize="5" AutoGenerateColumns="False" OnPageIndexChanging="gridweeks_PageIndexChanging">
<AlternatingRowStyle BackColor="#dddddd" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="weekmonth" HeaderText="Available Month" SortExpression="weekmonth" />
<asp:BoundField DataField="dayweek" HeaderText="Available Weeks" SortExpression="dayweek" />
<asp:TemplateField HeaderText="Edit / Delete">
<ItemTemplate>
<asp:LinkButton ID="lnkeditweek" runat="server" Style="color: black" CommandName="assign1" CommandArgument='<%#Eval("dayweek")+","+Eval("weekmonth")%>' OnClick="lnkeditweek_Click1"><i class="fa fa-pencil-square-o" style="color:#2389C9"></i></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#ffffff" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#32404E" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#32404E" ForeColor="White" HorizontalAlign="right" />
<RowStyle BackColor="#ffffff" BorderColor="#fff" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="batch" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT DISTINCT [dayweek], [weekmonth] FROM [tblslots]"></asp:SqlDataSource>
</div>
C# code
LinkButton btn = (LinkButton)(sender);
lbltxt.Visible = true;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
try
{
if (btn.CommandName == "assign1")
{
string[] commandArgs = btn.CommandArgument.ToString().Split(new char[] { ',' });
zeroval = commandArgs[0];
firstval = commandArgs[1];
for (int j = 0; j < gridweeks.Rows.Count; j++)
{
GridViewRow gw = gridweeks.Rows[j];
//string months = gw.Cells[0].Text;
// string weeks = gw.Cells[1].Text;
for (int i = 0; i < gridsem.Rows.Count; i++)
{
GridViewRow gs = gridsem.Rows[i];
string semester = gs.Cells[0].Text;
lbltxt.Text = "You are going to edit for Section : " + Request.QueryString["section"] + ", Week : " + zeroval + " , Session : " + Request.QueryString["session"] + " , Semester : " + semester + " , Month : " + firstval + "";
mp5edit.Show();
}
}
string longurl = "viewavailableweeks.aspx?&ins=" + Request.QueryString["ins"] + "§ion=" + Request.QueryString["section"] + "&session=" + Request.QueryString["session"] + "&academicyear=" + Request.QueryString["academicyear"] + "&month='" + firstval + "'+&week='" + firstval + "'";
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
longurl = uriBuilder.ToString();
}
}
this is my code ..while editing and deleting row index always taking zero on-wards...delete command not at all working....if i try to edit anything only 2nd row onwards its working...delete command not at all working..i think it is because of row index..please any one help me thanks in advance....
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Manager_Payments : System.Web.UI.Page
{
//SqlConnection con =new SqlConnection("Data Source=sqlexpress;Initial Catalog=isoqrmssys;User ID=sa;password=123456;Integrated Security=True");
Business BL = new Business();
//protected Int64 stf_ID, vmember;
//protected DateTime SRDT;
private System.Drawing.Color a;
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
loadgridview();
}
private void loadgridview()
{
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("select * from CustomerProfMain", con);
//string sql = "SELECT * FROM CustomerProfMain";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
//return ds.Tables[0];
Grd_View.DataSource = ds.Tables[0];
Grd_View.DataBind();
con.Close();
}
protected void Grd_View_RowCommand(Object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
int index = Grd_View.SelectedIndex;
if (e.CommandName == "Edit")
{
//string RowIndex = int.Parse(e.CommandArgument.ToString());
// Session["rowid"] = RowIndex;
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("Select * from CustomerProfMain where CustomerCode='" + e.CommandArgument.ToString() + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
dt=ds.Tables[0];
TextBox1.Text = dt.Rows[0]["CustomerName"].ToString();
TextBox2.Text=dt.Rows[0]["Address"].ToString();
TextBox3.Text=dt.Rows[0]["TellNo"].ToString();
TextBox4.Text=dt.Rows[0]["FaxNo"].ToString();
TextBox5.Text=dt.Rows[0]["Email"].ToString();
Button1.Text = "Update";
}
if (e.CommandName == "Delete")
{
int RowIndex = int.Parse(e.CommandArgument.ToString());
Session["rowid"] = RowIndex;
// DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("Delete from CustomerProfMain where CustomerCode='" + RowIndex + "' ", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
protected void Grd_View_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void Grd_View_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void Grd_View_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Button1.Text == "Add")
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(myStr);
con.Open();
string sql = string.Empty;
sql = "insert into CustomerProfMain(CustomerName,Address,TellNo,FaxNo,Email) values('" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() + "','" + TextBox3.Text.Trim() + "','" + TextBox4.Text.Trim() + "','" + TextBox5.Text.Trim() + "') ";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
Button1.Text = "Add";
loadgridview();
}
if (Button1.Text == "Update")
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(myStr);
con.Open();
string sql = string.Empty;
sql = "update CustomerProfMain set CustomerName='" + TextBox1.Text.Trim() + "',Address='" + TextBox2.Text.Trim() + "',TellNo='" + TextBox3.Text.Trim() + "',FaxNo='" + TextBox4.Text.Trim() + "',Email='" + TextBox5.Text.Trim() + "' where CustomerCode='" + Session["rowid"] + "'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
Button1.Text = "Add";
loadgridview();
}
}
}
"<asp:GridView ID="Grd_View" ShowFooter="True" runat="server" OnRowEditing="Grd_View_RowEditing" AutoGenerateColumns="False"
DataKeyNames="CustomerCode" cellpadding="4" OnRowCommand="Grd_View_RowCommand" GridLines="None"
AllowPaging="True" AllowSorting="True" CssClass="style2" ForeColor="#333333" Width="569px" OnRowDataBound="Grd_View_RowDataBound" OnRowDeleting="Grd_View_RowDeleting">
<FooterStyle BackColor="#555555" ForeColor="White" Font-Bold="True" />
<Columns>
<asp:BoundField DataField="CustomerCode" HeaderText="CustomerCode" InsertVisible="False"
ReadOnly="True" SortExpression="CustomerCode" />
<asp:BoundField DataField="CustomerName" HeaderText="CustomerName" SortExpression="CustomerName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="TellNo" HeaderText="TellNo" SortExpression="TellNo" />
<asp:BoundField DataField="FaxNo" HeaderText="FaxNo" SortExpression="FaxNo" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:CommandField ShowEditButton="true" SelectText="Edit" />
<asp:CommandField ShowDeleteButton="true" SelectText="Delete" />
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#777777" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#555555" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
"
Replace your grid view with this code
<asp:GridView ID="Grd_View" ShowFooter="True" runat="server" OnRowEditing="Grd_View_RowEditing" AutoGenerateColumns="False"
DataKeyNames="CustomerCode" CellPadding="4" OnRowCommand="Grd_View_RowCommand" GridLines="None"
AllowPaging="True" AllowSorting="True" CssClass="style2" ForeColor="#333333" Width="569px" OnRowDataBound="Grd_View_RowDataBound" OnRowDeleting="Grd_View_RowDeleting">
<FooterStyle BackColor="#555555" ForeColor="White" Font-Bold="True" />
<Columns>
<asp:BoundField DataField="CustomerCode" HeaderText="CustomerCode" InsertVisible="False"
ReadOnly="True" SortExpression="CustomerCode" />
<asp:BoundField DataField="CustomerName" HeaderText="CustomerName" SortExpression="CustomerName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="TellNo" HeaderText="TellNo" SortExpression="TellNo" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" CommandArgument='<%#Eval("CustomerCode")%>' CommandName="Edit" Text="Edit">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDelete" runat="server" CommandArgument='<%#Eval("CustomerCode")%>' CommandName="Delete" Text="Delete">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#777777" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#555555" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
You didn't set CommandArgument here we set it as CommandArgument='<%#Eval("CustomerCode")%>' to your edit button and delete button
Try doing the following...on page load bind the grid ONLY if it's not a postback...
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
loadgridview();
}
Then re-bind the grid at the end of the command event handler, I'll remove some data access logic for clarity...
protected void Grd_View_RowCommand(Object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
int index = Grd_View.SelectedIndex;
if (e.CommandName == "Edit")
{
//...
loadgridview();
}
if (e.CommandName == "Delete")
{
//...
loadgridview();
}
}
Try this and Set GridView's AutoPostback property to true
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
loadgridview();
}
}
If adding the two items in my lists i can only display the first updated item from the list in the detailsview , so my problem is that if i have 10 items in the list it should display the title on all them , then when i click on each hyperlinkbutton i want it to display that information about that title from the id
here is a image link of what i want to do.
http://i.stack.imgur.com/ZhJmc.jpg
protected void ButtonChoose_Click(object sender, EventArgs e)
{
try
{
if (DropDownListNewsFeed.SelectedItem.Value == "All")
{
SPWeb web = SPContext.Current.Web;
SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = "<Lists>" +
"<List ID=" + web.Lists.TryGetList("Staff News").ID.ToString() + " />" +
"<List ID=" + web.Lists.TryGetList("Company News").ID.ToString() + " />" +
"<List ID=" + web.Lists.TryGetList("Management News").ID.ToString() + " />" +
"</Lists>";
query.ViewFields = "<FieldRef Name=\"Title\" /><FieldRef Name=\"Date1\" Nullable=\"TRUE\"/>";
query.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE'></FieldRef></OrderBy>";
query.Webs = "<Webs Scope=\"SiteCollection\" />";
query.RowLimit = 10;
DataTable dt = web.GetSiteData(query);
DataView dv = new DataView(dt);
GridViewNewsFeed.DataSource = dv;
GridViewNewsFeed.DataBind();
}
else if(DropDownListNewsFeed.SelectedItem.Value == "Staff News")
{
SPWeb web = SPContext.Current.Web;
SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = "<Lists><List ID=" + web.Lists.TryGetList("Staff News").ID.ToString() + " /></Lists>";
query.ViewFields = "<FieldRef Name=\"Title\" /><FieldRef Name=\"Date1\" Nullable=\"TRUE\"/>";
query.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE'></FieldRef></OrderBy>";
query.Webs = "<Webs Scope=\"SiteCollection\" />";
query.RowLimit = 10;
DataTable dt = web.GetSiteData(query);
DataView dv = new DataView(dt);
GridViewNewsFeed.DataSource = dv;
GridViewNewsFeed.DataBind();
}
else if (DropDownListNewsFeed.SelectedItem.Value == "Management News")
{
SPWeb web = SPContext.Current.Web;
SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = "<Lists><List ID=" + web.Lists.TryGetList("Management News").ID.ToString() + " /></Lists>";
query.ViewFields = "<FieldRef Name=\"Title\" /><FieldRef Name=\"Date1\" Nullable=\"TRUE\"/>";
query.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE'></FieldRef></OrderBy>";
query.Webs = "<Webs Scope=\"SiteCollection\" />";
query.RowLimit = 10;
DataTable dt = web.GetSiteData(query);
DataView dv = new DataView(dt);
GridViewNewsFeed.DataSource = dv;
GridViewNewsFeed.DataBind();
}
else if (DropDownListNewsFeed.SelectedItem.Value == "Company News")
{
SPWeb web = SPContext.Current.Web;
SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = "<Lists><List ID=" + web.Lists.TryGetList("Company News").ID.ToString() + " /></Lists>";
query.ViewFields = "<FieldRef Name=\"Title\" /><FieldRef Name=\"Date1\" Nullable=\"TRUE\"/>";
query.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE'></FieldRef></OrderBy>";
query.Webs = "<Webs Scope=\"SiteCollection\" />";
query.RowLimit = 10;
DataTable dt = web.GetSiteData(query);
DataView dv = new DataView(dt);
GridViewNewsFeed.DataSource = dv;
GridViewNewsFeed.DataBind();
}
}
catch (Exception x)
{
LabelException.Text = x.Message;
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
try
{
SPWeb web = SPContext.Current.Web;
SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = "<Lists>" +
"<List ID=" + web.Lists.TryGetList("Staff News").ID.ToString() + " />" +
"<List ID=" + web.Lists.TryGetList("Company News").ID.ToString() + " />" +
"<List ID=" + web.Lists.TryGetList("Management News").ID.ToString() + " />" +
"</Lists>";
query.ViewFields = "<FieldRef Name=\"Title\" />" +
"<FieldRef Name=\"Authors\" />" +
"<FieldRef Name=\"Link\" />" +
"<FieldRef Name=\"Contents\" />" +
"<FieldRef Name=\"_Category\" />" +
"<FieldRef Name=\"Date1\" Nullable=\"TRUE\"/>";
//query.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE'></FieldRef></OrderBy>";
query.Webs = "<Webs Scope=\"SiteCollection\" />";
query.RowLimit = 10;
DataTable dt = web.GetSiteData(query);
DataView dv = new DataView(dt);
DetailsViewShowNews.DataSource = dv;
DetailsViewShowNews.DataBind();
}
catch (Exception x)
{
LabelException.Text = x.Message;
}
}
This is my asp gridview code:
<asp:GridView AutoGenerateColumns="False" ID="GridViewNewsFeed" runat="server" BackColor="White"
BorderColor="#DEDFDE" BorderStyle="Solid" BorderWidth="1px" CellPadding="4"
EnableModelValidation="True" GridLines="Vertical" ForeColor="Black" >
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" OnClick="LinkButton1_Click" runat="server" Text='<%# Bind("Title") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:templatefield headertext="Date">
<itemtemplate>
<asp:label id="lblDate" runat="server" text='<%# DateTime.Parse(Eval("Date1").ToString()).ToString("d") %>' />
</itemtemplate>
</asp:templatefield>
</Columns>
</asp:GridView>
This is my asp detailsview code:
<asp:DetailsView AutoGenerateRows="False" ID="DetailsViewShowNews" runat="server"
BackColor="White" BorderColor="#336666" BorderWidth="1px"
CellPadding="4" EnableModelValidation="True" GridLines="Horizontal"
Height="226px" Width="301px" BorderStyle="Solid" >
<EditRowStyle BackColor="#339966" ForeColor="White" Font-Bold="True" />
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White"
HorizontalAlign="Center" />
<Fields>
<asp:TemplateField >
<ItemTemplate>
<asp:Label ID="Label12" runat="server" Text='<%#Eval("Title") %>' Font-Size="Large" Font-Bold="True"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox22" runat="server" Text='<%#Eval("Contents") %>' TextMode="MultiLine" Height="100%" BorderStyle="None" ReadOnly="True" Width="250px" style="overflow:auto;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label72" runat="server" Text='<%#Eval("_Category") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label52" runat="server" Text='<%#Eval("Authors") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label32" runat="server" Text='<%#DateTime.Parse(Eval("Date1").ToString()).ToString("d") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label42" runat="server" Text='<%#Eval("Link") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButtonComment" OnClick="LinkButtonComment_Click" runat="server">Leave a comment</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Fields>
<RowStyle BackColor="White" ForeColor="#333333" />
</asp:DetailsView>
Firstly you can reduce your code and make it more generic like this:
try
{
SPWeb web = SPContext.Current.Web;
SPSiteDataQuery query = new SPSiteDataQuery();
switch (DropDownListNewsFeed.SelectedItem.Value)
{
case "ALL":
query.Lists = "<Lists>" +
"<List ID=" + web.Lists.TryGetList("Staff News").ID.ToString() + " />" +
"<List ID=" + web.Lists.TryGetList("Company News").ID.ToString() + " />" +
"<List ID=" + web.Lists.TryGetList("Management News").ID.ToString() + " />" +
"</Lists>";
break;
case "Staff News":
query.Lists = "<Lists><List ID=" + web.Lists.TryGetList("Staff News").ID.ToString() + " /></Lists>";
break;
case "Management News":
query.Lists = "<Lists><List ID=" + web.Lists.TryGetList("Management News").ID.ToString() + " /></Lists>";
break;
case "Company News":
query.Lists = "<Lists><List ID=" + web.Lists.TryGetList("Company News").ID.ToString() + " /></Lists>";
break;
}
query.ViewFields = "<FieldRef Name=\"Title\" /><FieldRef Name=\"Date1\" Nullable=\"TRUE\"/>";
query.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE'></FieldRef></OrderBy>";
query.Webs = "<Webs Scope=\"SiteCollection\" />";
query.RowLimit = 10;
DataTable dt = web.GetSiteData(query);
DataView dv = new DataView(dt);
GridViewNewsFeed.DataSource = dv;
GridViewNewsFeed.DataBind();
}
catch (Exception x)
{
LabelException.Text = x.Message;
}
About your problem:
try to pass item ID (the best is to pass UniqueId) as a "CommandArgument" on the link button. To specify this you can just bind an item ID field to CommandArgument property:
<asp:LinkButton ID="LinkButton1" OnClick="LinkButton1_Click" CommandArgument="<%# Bind("ItemId") %>" runat="server" Text='<%# Bind("Title") %>'></asp:LinkButton>
On the code behind when button is clicked you can get it using next lines of code:
LinkButton button = (LinkButton) sender;
string itemID = button.CommandArgument;
After you have your ID just get it with clause where:
query.Query = <Where>
<Eq>
<FieldRef Name='ID' />
<Value Type='Text'>ID</Value>
</Eq>
</Where>";
EDITED:
To get a field from SharePoint add "UniqueId" field in
query.VieweFields. this will get it from Sharepoint and generate in
the DataTable:
query.ViewFields = "<FieldRef Name=\"UniqueId\"/>";
To get value of this field on code behind in the button event methode
do following:
SPFieldLookupValue f = new SPFieldLookupValue(button.CommandArgument);
string itemID = f.LookupValue;
Hope it helps,
Andrew
I am a new ASP.NET developer and I am developing a simple registration system. I am trying now to let the system administrator being able to send reminders to the registered users before the start date of the event. All the avaliable events will be listed in a GridView with a button for sending reminders to the registered users in that event.
For your information, I have the following database design:
Employees Table: NetID, Name
Events Table: ID, Title
BookingDetails Table: BookingID, EventID, NetID
**Please note that NetID is the username of the employee
ASP.NET Code:
<asp:GridView ID="ListOfAvailableEvents_GrivView" runat="server"
AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333"
GridLines="None" AllowPaging="True">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" CssClass="generaltext" />
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" />
<asp:BoundField DataField="StartDateTime" HeaderText="Start Date & Time" SortExpression="StartDateTime" />
<asp:BoundField DataField="EndDateTime" HeaderText="End Date & Time" SortExpression="EndDateTime" />
<asp:BoundField DataField="NumberOfSeats" HeaderText="Number of Seats" SortExpression="NumberOfSeats" />
<asp:BoundField DataField="Number of Bookings" HeaderText="Number of Bookings" ReadOnly="True"
SortExpression="Number of Bookings" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button ID="sendButton" runat="server" CssClass="button" Text="Send Reminder →"
OnClick="btnSend_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle Font-Bold="True" CssClass="complete" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:PM_RegistrationSysDBConnectionString %>"
SelectCommand="SELECT Events.Title, Events.Description, Events.Location, Events.StartDateTime, Events.EndDateTime, Events.NumberOfSeats, COUNT(BookingDetails.BookingID) AS [Number of Bookings] FROM Events INNER JOIN BookingDetails ON Events.ID = BookingDetails.EventID WHERE (Events.IsActive = 1) GROUP BY Events.Title, Events.Description, Events.Location, Events.StartDateTime, Events.EndDateTime, Events.NumberOfSeats ORDER BY Events.StartDateTime DESC"></asp:SqlDataSource>
C# Code:
protected void btnSend_Click(object sender, EventArgs e)
{
GridViewRow gvrow = (GridViewRow)(((Button)sender)).NamingContainer;
HiddenField1.Value = ListOfAvailableEvents_GrivView.DataKeys[gvrow.RowIndex].Value.ToString();
string title = gvrow.Cells[0].Text;
string description = gvrow.Cells[1].Text;
string location = gvrow.Cells[2].Text;
string startDateTime = gvrow.Cells[3].Text;
string endDateTime = gvrow.Cells[4].Text;
string connString = ".............................;";
using (SqlConnection conn = new SqlConnection(connString))
{
var sbEmailAddresses = new System.Text.StringBuilder(2000);
int eventID = Convert.ToInt32(HiddenField1.Value);
//Open DB connection
conn.Open();
string cmdText = #"SELECT dbo.Events.Title, dbo.Employees.NetID
FROM dbo.BookingDetails INNER JOIN
dbo.Events ON dbo.BookingDetails.EventID = #EventID INNER JOIN
dbo.Employees ON dbo.BookingDetails.NetID = dbo.Employees.NetID";
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.Parameters.AddWithValue("#EventID", eventID);
cmd.ExecuteNonQuery();
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
while (reader.Read())
{
var sName = reader.GetString(0);
if (!string.IsNullOrEmpty(sName))
{
if (sbEmailAddresses.Length != 0)
{
sbEmailAddresses.Append(", ");
}
sbEmailAddresses.Append(sName).Append("#appServer.com");
}
}
}
reader.Close();
var sEMailAddresses = sbEmailAddresses.ToString();
string body = "..........................";
int sendCount = 0;
List<string> addressList = new List<string>(sEMailAddresses.Split(','));
StringBuilder addressesToSend = new StringBuilder();
for (int userIndex = 0; userIndex < addressList.Count; userIndex++)
{
sendCount++;
if (addressesToSend.Length > 0)
addressesToSend.Append(",");
addressesToSend.Append(addressList[userIndex]);
if (sendCount == 10 || userIndex == addressList.Count - 1)
{
SendEmail(addressesToSend.ToString(), "", "Registration REMINDER Notification", body, true);
addressesToSend.Clear();
sendCount = 0;
}
}
cmd.ExecuteNonQuery();
}
//reset the value of hiddenfield
HiddenField1.Value = "-1";
}
}
protected void SendEmail(string toAddresses, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml)
{
SmtpClient sc = new SmtpClient("MAIL ADDRESS");
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("app#appServer.com", "Registration System");
// In case the mail system doesn't like no to recipients. This could be removed
//msg.To.Add("app#appServer.com");
msg.Bcc.Add(toAddresses);
msg.Subject = MailSubject;
msg.Body = MessageBody;
msg.IsBodyHtml = isBodyHtml;
sc.Send(msg);
}
catch (Exception ex)
{
throw ex;
// something bad happened
//Response.Write("Something bad happened!");
}
}
But I could not be able to send any emails. Could you please tell me why?
UPDATE:
I wrote the code and when I run it, I did not get any error. I tried to debug it and when I did that I found the call to SendEmail(string toAddresses, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml) method is not working and I don't know why.
So could you please tell me how I can send emails to the registered users of the selected event?
for (int userIndex = 0; userIndex < addressList.Count-1; userIndex++)
{
check this for loop once