My requirement is same as stockoverflow tag display. I have a repeater control in which i am binding few columns. Now i want to display different tags associated with the corresponding thread. Please find the code...
<asp:Repeater ID="repForumThread" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<table width="100%">
<tr>
<td>
<asp:HyperLink ID="hlCategory" runat="server" NavigateUrl='<%#GetRouteUrl("CategoryRoute", new {CategoryNo= Eval("CategoryId"),CategoryName = Eval("CategoryTitle").ToString().ToLower().Trim().Replace(" ","-")}) %>'
Text='<%# DataBinder.Eval(Container.DataItem, "CategoryTitle")%>'></asp:HyperLink>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblThreadTitle" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "ThreadTitle") %>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:HyperLink ID="hlThreadCreatedBy" runat="server" NavigateUrl='<%#GetRouteUrl("ProfileRoute", new {Member= Eval("MemberId"),MemberName = Eval("ThreadCreatedBy").ToString().ToLower().Trim().Replace(" ","-")}) %>'
Text='<%# DataBinder.Eval(Container.DataItem, "ThreadCreatedBy")%>'></asp:HyperLink>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCreatedOn" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"ThreadCreatedOn") %>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblDescription" runat="server" CssClass="HeaderTextSmall" Text='<%#DataBinder.Eval(Container.DataItem, "ThreadDescription")%>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:PlaceHolder ID="phTag" runat="server"></asp:PlaceHolder>
</td>
</tr>
</table>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
public void BindRepForumThread()
{
SqlConnection dBConnection = null;
try
{
dBConnection = new SqlConnection();
DataTable dtTag = new DataTable();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_GetThreadDetails", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#threadId", SqlDbType.Int).Value = threadId;
dBConnection.Open();
dataAdapter.SelectCommand = cmd;
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
DataTable dtThread = new DataTable();
DataRow drThread;
dtThread.Columns.Add("ThreadId");
dtThread.Columns.Add("CategoryId");
dtThread.Columns.Add("CategoryTitle");
dtThread.Columns.Add("ThreadTitle");
dtThread.Columns.Add("ThreadDescription");
dtThread.Columns.Add("ThreadCreatedBy");
dtThread.Columns.Add("ThreadCreatedOn");
dtThread.Columns.Add("MemberId");
dtThread.Columns.Add("TagId");
dtThread.Columns.Add("TagDescription");
foreach (DataRow dr in ds.Tables[0].Rows)
{
drThread = dtThread.NewRow();
drThread["ThreadId"] = dr["T_ThreadId"];
drThread["CategoryId"] = dr["C_CategoryId"];
drThread["CategoryTitle"] = dr["C_CategoryTitle"];
drThread["ThreadTitle"] = dr["T_ThreadTitle"];
drThread["ThreadDescription"] = dr["T_ThreadDescription"];
drThread["ThreadCreatedBy"] = dr["Mem_MemberUserName"];
drThread["ThreadCreatedOn"] = dr["T_ThreadCreatedOn"];
drThread["MemberId"] = dr["T_ThreadCreatedBy"];
if (ds.Tables[1].Rows.Count > 0)
{
phTag.Controls.Clear();
foreach (DataRow dr1 in ds.Tables[1].Rows)
{
HyperLink hlTag = new HyperLink();
hlTag.Text = dr1["Tg_TagName"].ToString();
int TagId = Convert.ToInt32(dr1["Tg_TagId"].ToString());
hlTag.ID = "hlTag" + TagId.ToString();
hlTag.NavigateUrl = hlTag.GetRouteUrl("TagRoute", new { Id = TagId, TagName = hlTag.Text.ToString().ToLower().Trim().Replace(" ", "-") });
phTag.Controls.Add(hlTag);
}
}
dtThread.Rows.Add(drThread);
}
repForumThread.DataSource = dtThread;
repForumThread.DataBind();
dBConnection.Close();
}
}
catch (Exception Ex)
{
throw Ex;
}
finally
{
// Close data reader object and database connection
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
}
evreything is working fine. I am able to generate hyperlinks dynamically but I am not able to display the created hyperlinks & it is throwing the error "Object reference not set to an instance of an object" for placeholder.
Thanks in advance.
Well I have resolved the problem. I was missing OnItemCreate function of repeater cotrol where we can findcontrol of a place holder & then we can add hyperlinks dynamically.
protected void repForumThread_ItemCrteated(object sender, RepeaterItemEventArgs e)
{
DataRowView drv = e.Item.DataItem as DataRowView;
DataTable dtTag = new DataTable();
if (Cache["TagData"] != null)
{
dtTag = (DataTable)Cache["TagData"];
}
if (dtTag.Rows.Count > 0)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
PlaceHolder plTag = e.Item.FindControl("phTag") as PlaceHolder;
if (plTag != null)
{
plTag.Controls.Clear();
foreach (DataRow dr1 in dtTag.Rows)
{
HyperLink hlTag = new HyperLink();
hlTag.Text = dr1["Tg_TagName"].ToString();
int TagId = Convert.ToInt32(dr1["Tg_TagId"].ToString());
hlTag.ID = "hlTag" + TagId.ToString();
hlTag.NavigateUrl = hlTag.GetRouteUrl("TagRoute", new { Id = TagId, TagName = hlTag.Text.ToString().ToLower().Trim().Replace(" ", "-") });
plTag.Controls.Add(hlTag);
}
}
}
}
}
Related
I have a asp calendar utility in ascx page. I want to unselect the selected date on second click on the same date. The following are my codes. Kindly help in this.
<%# Control Language="C#" AutoEventWireup="true"CodeFile="Calendar.ascx.cs"Inherits="WebUserControl" %>
<table>
<tr>
<td width="100%">
<asp:DropDownList ID="ddlyear" runat="server"
onselectedindexchanged="ddlyear_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="2014" Value="2014" Selected="True"></asp:ListItem>
<asp:ListItem Text="2015" Value="2015"></asp:ListItem>
<asp:ListItem Text="2016" Value="2016"></asp:ListItem>
<asp:ListItem Text="2017" Value="2017"></asp:ListItem>
<asp:ListItem Text="2018" Value="2018"></asp:ListItem>
<asp:ListItem Text="2019" Value="2019"></asp:ListItem>
<asp:ListItem Text="2020" Value="2020"></asp:ListItem>
<asp:ListItem Text="2021" Value="2021"></asp:ListItem>
<asp:ListItem Text="2022" Value="2022"></asp:ListItem>
<asp:ListItem Text="2023" Value="2023"></asp:ListItem>
<asp:ListItem Text="2024" Value="2024"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td width="100%" dir="ltr">
<asp:DataList ID="DataList1" runat="server" HorizontalAlign="Center"
RepeatDirection="Horizontal" RepeatColumns="4"
onitemdatabound="DataList1_ItemDataBound"
>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="txt1" runat="server" Text='<%#Eval("Month") %>' Visible="false" Font-Names="Arial"></asp:Label>
<asp:HiddenField ID="hdn1" runat="server" />
<asp:Calendar ID="Calendar1" runat="server" NextPrevFormat="CustomText" SelectionMode="Day" NextMonthText="" PrevMonthText="" Font-Names="A" OtherMonthDayStyle-BorderStyle="NotSet" OtherMonthDayStyle-Wrap="False" OtherMonthDayStyle-ForeColor="#CCCCCC">
<TitleStyle
BackColor="#6EC347"
ForeColor="White"
Height="36"
Font-Size="Large"
Font-Names="Arial"
/>
<SelectedDayStyle
BackColor="Green"
BorderColor="SpringGreen"
/>
</asp:Calendar>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
My code behind for this ascx page is
public partial class WebUserControl : System.Web.UI.UserControl
{
int month = 1;
public event EventHandler YearChanged;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadcalendar();
}
}
private void loadcalendar()
{
DataTable dt = new DataTable();
dt.Columns.Add("Month", typeof(string));
dt.Rows.Add("January");
dt.Rows.Add("February");
dt.Rows.Add("March");
dt.Rows.Add("April");
dt.Rows.Add("May");
dt.Rows.Add("June");
dt.Rows.Add("July");
dt.Rows.Add("August");
dt.Rows.Add("September");
dt.Rows.Add("October");
dt.Rows.Add("Novemeber");
dt.Rows.Add("December");
DataList1.DataSource = dt;
DataList1.DataBind();
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
string year = ddlyear.SelectedValue.ToString();
String str = ((Label)e.Item.FindControl("txt1")).Text;
DateTime Now = DateTime.Now;
DateTime TempDate = new DateTime(Convert.ToInt32(year), month, 1);
// DateTime TempDate = new DateTime(Now.Year,Now.Month, 1);
((Calendar)e.Item.FindControl("Calendar1")).VisibleDate = TempDate;
month = month + 1;
}
}
protected void ddlyear_SelectedIndexChanged(object sender, EventArgs e)
{
loadcalendar();
YearChanged(sender, e);
}
}
My Aspx.cs page code is like this
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
string eid;
string ename = DropDownList2.SelectedValue.ToString();
if (ename == "1")
{
eid = "1";
}
else
{
eid = "2";
}
int cid = Int32.Parse(DropDownList1.SelectedValue.ToString());
//String sqlSelect = String.Format("Select Customer_Id from Customer where Customer_Name='{0}'", cname);
//SqlCommand cmd1 = new SqlCommand(sqlSelect, cnn);
//int cid = (int)cmd1.ExecuteScalar();
DataList dl;
dl = ((DataList)patchCalendar.FindControl("DataList1"));
foreach (DataListItem dli in dl.Items)
{
string month = Convert.ToString(((Label)dli.FindControl("txt1")).Text);
string day = Convert.ToString(((Calendar)dli.FindControl("Calendar1")).SelectedDate.Day);
string year = Convert.ToString(((Calendar)dli.FindControl("Calendar1")).SelectedDate.Year);
string date = ((Calendar)dli.FindControl("Calendar1")).SelectedDate.ToShortDateString();
if (date == "1/1/0001")
{
year = null;
date = null;
day = null;
}
else
{
SqlCommand cmd = new SqlCommand("insert into Patching_Dates values(#cid,#eid,#year,#month,#day,#date)", cnn);
cmd.Parameters.AddWithValue("#cid", cid);
cmd.Parameters.AddWithValue("#eid", eid);
cmd.Parameters.AddWithValue("#year", year);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#day", day);
cmd.Parameters.AddWithValue("#date", date);
cmd.ExecuteNonQuery();
}
}
cnn.Close();
string act = "Patching Dates Added";
cnn.Open();
SqlCommand cmd2 = new SqlCommand("insert into Logs values(#Username,#Activity,#Time)", cnn);
cmd2.Parameters.AddWithValue("#Username", (string)(Session["user"]));
cmd2.Parameters.AddWithValue("#Activity", act);
cmd2.Parameters.AddWithValue("#Time", System.DateTime.Now.ToString());
cmd2.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
First check Calendar1 control having value if yes then reset it by this
Calendar1.SelectedDates.Clear();
I have a Datalist, inside itemtemplate i had two labels and one button.
I want to retrieve the row data of datalist row.
My .aspx page is:
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<table width="100%">
<tr>
<td>
<asp:Label ID="lblid11" runat="server" Text='<%#Eval("SubMenu_Id") %>' />
</td>
<td>
<asp:Label ID="lblid12" runat="server" Text='<%#Eval("SubMenu_Name") %>' />
</td>
<td>
<asp:Label ID="lblid13" runat="server" Text='<%#Eval("SubMenu_Price") %>' />
</td>
<td>
<asp:Button ID="btninside" runat="server" CommandName="call" Text="click me" onclick="btninside_Click" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
and My .CS page is
public partial class Datalist_Button : System.Web.UI.Page
{
string s = WebConfigurationManager.ConnectionStrings["FoodPlanetConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
public void BindDataList()
{
SqlConnection con = new SqlConnection(s);
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Menu", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataList1.DataSource = ds;
DataList1.DataBind();
con.Close();
}
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "call")
{
DataListItem item = (DataListItem)(((Button)(e.CommandSource)).NamingContainer);
string text = ((Label)item.FindControl("lblid12")).Text;
}
}
pleae help me,my code is not working
Try this.
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "call")
{
string text = ((Label)DataList1.Items[e.Item.ItemIndex].FindControl("lblid12")).Text;
}
}
I am trying to move the specific gridview data into the excel file but I am getting an error as object reference not set to the instance of an object
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="Chckcol0" runat="server" Checked="true"/>
<asp:Label ID="lbl_catid" runat="server" Text=" CategoryID"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl_catid" runat="server" Text='<%# Eval("cat_id")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="Chckcol1" runat="server" Checked="true"/>
<asp:Label ID="lbl_catname" runat="server" Text="category Name"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl_categoryname" runat="server" Text='<%# Eval("categoryname")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="Chckcol2" runat="server" Checked="true"/>
<asp:Label ID="description" runat="server" Text="description"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl_description" runat="server" Text='<%# Eval("description")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And my code behind:
public partial class _Default : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection("Data Source=localhost;Database=mylibrary_db;User ID=root;Password=MyLuck2010");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgrid();
}
}
protected void fillgrid()
{
MySqlDataAdapter da = new MySqlDataAdapter("select cat_id,categoryname,description from library_category", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void getcheckedgridview()
{
CheckBox chkCol0 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol0");
CheckBox chkCol1 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol1");
CheckBox chkCol2 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol2");
ArrayList arr;
if (ViewState["States"] == null)
{
arr = new ArrayList();
}
else
{
arr = (ArrayList)ViewState["States"];
}
arr.Add(chkCol0.Checked);
arr.Add(chkCol1.Checked);
arr.Add(chkCol2.Checked);
ViewState["States"] = arr;
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
ArrayList arr = (ArrayList)ViewState["States"];
GridView1.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[0]);
GridView1.HeaderRow.Cells[1].Visible = Convert.ToBoolean(arr[1]);
GridView1.HeaderRow.Cells[2].Visible = Convert.ToBoolean(arr[2]);
GridView1.HeaderRow.Cells[0].FindControl("chkCol0").Visible = false;
GridView1.HeaderRow.Cells[1].FindControl("chkCol1").Visible = false;
GridView1.HeaderRow.Cells[2].FindControl("chkCol2").Visible = false;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
row.Cells[0].Visible = Convert.ToBoolean(arr[0]);
row.Cells[1].Visible = Convert.ToBoolean(arr[1]);
row.Cells[2].Visible = Convert.ToBoolean(arr[2]);
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
}
The fault is most likely to be with the Convert.ToBoolean(arr[0]); (see the line GridView1.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[0]);)
I would put a break tag on the faulting line and see what the value of arr[0] is. I would guess arr is empty or null and your ViewState is not returning the data you are expecting. This maybe because your method getcheckedgridview() is not called by your code (or at least, not by the code you've displayed)!
You could try (where the only change is the first line of the method)
protected void btnExportExcel_Click(object sender, EventArgs e)
{
getcheckedgridview();//Only change to your code
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
ArrayList arr = (ArrayList)ViewState["States"];
GridView1.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[0]);
GridView1.HeaderRow.Cells[1].Visible = Convert.ToBoolean(arr[1]);
GridView1.HeaderRow.Cells[2].Visible = Convert.ToBoolean(arr[2]);
GridView1.HeaderRow.Cells[0].FindControl("chkCol0").Visible = false;
GridView1.HeaderRow.Cells[1].FindControl("chkCol1").Visible = false;
GridView1.HeaderRow.Cells[2].FindControl("chkCol2").Visible = false;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
row.Cells[0].Visible = Convert.ToBoolean(arr[0]);
row.Cells[1].Visible = Convert.ToBoolean(arr[1]);
row.Cells[2].Visible = Convert.ToBoolean(arr[2]);
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
Edit
Based upon your comments, I think the error message is now due to your code not finding the control in question. So
CheckBox chkCol0 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol0");
does not find the control called "chkCol0" and so therefore chkCol0 is null.
I am new to ASP.NET
ERROR: "The FormView 'FormView1' fired event ItemInserting which wasn't handled. "
I have a FormView that set to Insert Mode when the page first initially loaded. I also want to pre-populated the values in those input textboxes and dropdownlists. So I was able to make it works by using the code behind and write the values to those boxes, but when I click "Insert" LinkButton, it give me that error.
Here is my FormView codes:
<asp:FormView ID="FormView1" DefaultMode="Insert" runat="server"
DateSourceID="dsApprovedCreateNew"
DataKeyNames="ApprovedID"
>
<InsertItemTemplate>
<table class="FormDetail" width="95%" height="100%" align="center" class="FormDetail" >
<tr>
<td class="right">MDF Name:</td>
<td>
<asp:TextBox ID="MDFName" runat="server" Width="50%" Text='<%# Bind("MDFName") %>' > </asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="MDFName" Text="The MDFName field is required!" runat="server" />
</td>
</tr>
<tr>
<td>Vendor Name</td>
<td>
<asp:DropDownList ID="ddlVendorList" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td>Vendor BU</td>
<td>
<asp:DropDownList ID="ddlVendorBUList" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td class="right">Vendor Quarter:</td>
<td>
<asp:DropDownList ID="VendorQuarter" runat="server" Text='<%# Bind("VendorQuarter") %>'
AppendDataBoundItems="true">
<asp:ListItem Value="Q1">Q1</asp:ListItem>
<asp:ListItem Value="Q2">Q2</asp:ListItem>
<asp:ListItem Value="Q3">Q3</asp:ListItem>
<asp:ListItem Value="Q4">Q4</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="right">MDF Amount:</td>
<td>
<asp:TextBox ID="MDFAmount" runat="server" Width="20%" TextMode="SingleLine" Text='<%# Bind("VendorQuarter") %>'></asp:TextBox>
<asp:CustomValidator ID="RangeValidator3" runat="server" ControlToValidate="MDFAmount"
ErrorMessage="Enter numerical value only!" ClientValidationFunction="validateNumber"/>
<asp:RequiredFieldValidator ControlToValidate="MDFAmount" Text="The MDFAmount field is required!" runat="server" />
<%--
<asp:RegularExpressionValidator ID="RangeValidator4" runat="server" ControlToValidate="MDFAmount"
Display="Dynamic" ErrorMessage="*Enter numerical value only"
ValidationExpression="^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$"/>
--%>
</td>
</tr>
<tr>
<td class="right">Begin Date (mm/dd/yyyy):</td>
<td>
<asp:TextBox ID="BeginDate" runat="server" Width="50%" TextMode="SingleLine" DataFormatString="{0:MM/dd/yyyy}"
ApplyFormatInInsertMode="true" ></asp:TextBox>
<asp:RegularExpressionValidator ID="RangeValidator1" runat="server" ControlToValidate="BeginDate" ForeColor="Red"
ErrorMessage="Enter Valid Date in dd/mm/yyyy format." SetFocusOnError="True" Display="Dynamic" Type="Date"
ValidationExpression="^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d$">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="right">End Date (mm/dd/yyyy):</td>
<td>
<asp:TextBox ID="EndDate" runat="server" Width="50%"></asp:TextBox>
<asp:RegularExpressionValidator ID="RangeValidator2" runat="server" ControlToValidate="EndDate" ForeColor="Red"
ErrorMessage="Enter Valid Date in dd/mm/yyyy format." SetFocusOnError="True" Display="Dynamic" Type="Date"
ValidationExpression="^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d$"/>
</td>
</tr>
<tr>
<td class="right">MDF Summary:</td>
<td>
<asp:TextBox ID="MDFSummary" TextMode="MultiLine" Width="50%" Height="100" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="right">Status:</td>
<td>
<asp:DropDownList ID="Status" runat="server"
AppendDataBoundItems="true">
<asp:ListItem>Active</asp:ListItem>
<asp:ListItem>Inactive</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2">
<asp:linkbutton id="InsertButton"
text="Insert"
commandname="Insert"
runat="server" />
<asp:linkbutton id="CancelButton"
text="Cancel"
commandname="Cancel"
runat="server" />
</td>
</tr>
</table>
<asp:HiddenField ID="CreatedBy" runat="server" value="44444"/>
</InsertItemTemplate>
</asp:FormView>
<asp:sqldatasource id="dsApprovedCreateNew"
connectionstring="<%$ ConnectionStrings:ConnectionString%>"
SelectCommand="SELECT p.*
, (SELECT VendorName FROM MDF_Vendor WHERE VendorID = p.VendorID) AS VendorName
, (SELECT VendorBUName FROM MDF_VendorBU WHERE VendorBUID = p.VendorBUID) AS VendorBUName
FROM dbo.MDF_Proposed p Where p.ProposedID = 63"
InsertCommand = "INSERT INTO [MDF_Approved] ([VendorID], [VendorBUID], [MDFName]
, [BeginDate], [EndDate], [CreatedBy])
VALUES (#VendorID, #VendorBUID, #MDFName, #BeginDate, #EndDate, '1234') "
runat="server">
<SelectParameters>
<asp:QueryStringParameter Name="ProposedID" QueryStringField="ProposedID" runat="server" />
</SelectParameters>
</asp:sqldatasource>
</form>
The Code Behind (I am a newbie, so don't laugh at my codes, suggestions are welcome)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//FormView1.PreRender += FormView1_PreRender;
//FormView1.DataBinding += FormView1_DataBinding;
if (!IsPostBack)
{
//Response.Write("ProposedID: " + Request.QueryString["ProposedID"]);
int ProposedID = FetchQueryStringIdentifierByKey("ProposedID");
Response.Write("ProposedID : " + ProposedID);
//FormView1.DataSource = this.GetData(ProposedID);
//FormView1.DataBind();
FillFormValues(ProposedID);
//GetData(ProposedID);
}
}
protected int FetchQueryStringIdentifierByKey(string key)
{
int identifier;
var isInt = int.TryParse(Request.QueryString[key], out identifier);
return (isInt) ? identifier : 0;
}
private DataSet GetData(int RecID)
{
string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string query = "SELECT * FROM MDF_Proposed WHERE ProposedID = 63";
SqlCommand cmd = new SqlCommand(query);
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("#RecID", SqlDbType.Int, 10);
param[0].Value = 1; // RecID;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
private void FillFormValues(int RecID)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM MDF_Proposed WHERE ProposedID = 63";
cmd.Parameters.AddWithValue("#RecID", RecID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
if (FormView1.CurrentMode == FormViewMode.Insert)
{
Response.Write("The Mode: " + FormView1.CurrentMode);
TextBox MDFName = (TextBox)FormView1.FindControl("MDFName");
MDFName.Text = objDs.Tables[0].Rows[0]["MDFName"].ToString();
TextBox MDFAmount = (TextBox)FormView1.FindControl("MDFAmount");
MDFAmount.Text = objDs.Tables[0].Rows[0]["MDFAmount"].ToString();
TextBox BeginDate = (TextBox)FormView1.FindControl("BeginDate");
BeginDate.Text = FormatDateNoTime(objDs.Tables[0].Rows[0]["BeginDate"].ToString());
TextBox EndDate = (TextBox)FormView1.FindControl("EndDate");
EndDate.Text = FormatDateNoTime(objDs.Tables[0].Rows[0]["EndDate"].ToString());
fillVendorDLL(Convert.ToInt32(objDs.Tables[0].Rows[0]["VendorID"]));
fillVendorBUDLL(Convert.ToInt32(objDs.Tables[0].Rows[0]["VendorID"]), Convert.ToInt32(objDs.Tables[0].Rows[0]["VendorBUID"]));
TextBox MDFSummary = (TextBox)FormView1.FindControl("MDFSummary");
MDFSummary.Text = objDs.Tables[0].Rows[0]["MDFSummary"].ToString();
}
else
{
Response.Write("Nothing");
}
}
else
{
Response.Write("No Record found");
}
}
protected void fillVendorDLL(int VendorID)
{
//DropDownList ddlVendor = (DropDownList)sender;
// DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl("updateVendorName");
//DropDownList ddlVendor = (DropDownList)sender;
//DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl(ddlID);
DropDownList ddlVendor =
(DropDownList)FormView1.FindControl("ddlVendorList");
if (ddlVendor != null)
{
//Response.Write("SelectChanged");
//int VendorID = Convert.ToInt32(ddlVendor.SelectedValue.ToString());
//Response.Write("VendorID: " + VendorID);
ddlVendor.Items.Clear();
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorID, VendorName FROM dbo.MDF_Vendor";
cmd.Parameters.AddWithValue("#VendorID", VendorID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in objDs.Tables[0].Rows)
{
ddlVendor.Items.Insert(0, new ListItem((dr["VendorName"]).ToString(), (dr["VendorID"]).ToString()));
ddlVendor.SelectedValue = Convert.ToString(VendorID);
}
}
}
}
protected void fillVendorBUDLL(int VendorID, int VendorBUID)
{
//DropDownList ddlVendor = (DropDownList)sender;
// DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl("updateVendorName");
//DropDownList ddlVendor = (DropDownList)sender;
//DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl(ddlID);
DropDownList ddlVendorBU =
(DropDownList)FormView1.FindControl("ddlVendorBUList");
if (ddlVendorBU != null)
{
//Response.Write("SelectChanged");
//int VendorID = Convert.ToInt32(ddlVendor.SelectedValue.ToString());
//Response.Write("VendorID: " + VendorID);
ddlVendorBU.Items.Clear();
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorBUID, VendorBUName FROM dbo.MDF_VendorBU WHERE VendorID = #VendorID";
cmd.Parameters.AddWithValue("#VendorID", VendorID);
cmd.Parameters.AddWithValue("#VendorBUID", VendorBUID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in objDs.Tables[0].Rows)
{
ddlVendorBU.Items.Insert(0, new ListItem((dr["VendorBUName"]).ToString(), (dr["VendorBUID"]).ToString()));
ddlVendorBU.SelectedValue = Convert.ToString(VendorBUID);
}
}
}
}
public string GetConnectionString(){
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
private void ExecuteInsert(string VendorName, string VendorBU, string MDFAmount
, string StartDate, string EndDate, string VendorQuarter, string MDFName, String MDFSummary, string Status, string CreatedBy)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO MDF_Proposed (VendorID, VendorBUID, MDFAmount, BeginDate, EndDate, VendorQuarter
, MDFName, MDFSummary, Status, CreatedBy) VALUES "
+ " (#VendorID, #VendorBUID, #MDFAmount, #StartDate, #EndDate, #VendorQuarter, #MDFName, #MDFSummary, #Status, #CreatedBy)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[10];
param[0] = new SqlParameter("#VendorID", SqlDbType.VarChar, 50);
param[1] = new SqlParameter("#VendorBUID", SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#MDFAmount", SqlDbType.Decimal);
param[2].Precision = 19;
param[2].Scale = 4;
param[3] = new SqlParameter("#StartDate", SqlDbType.DateTime);
param[4] = new SqlParameter("#EndDate", SqlDbType.DateTime);
param[5] = new SqlParameter("#VendorQuarter", SqlDbType.VarChar, 50);
param[6] = new SqlParameter("#MDFName", SqlDbType.VarChar, 50);
param[7] = new SqlParameter("#MDFSummary", SqlDbType.VarChar, 2000);
param[8] = new SqlParameter("#Status", SqlDbType.VarChar, 50);
param[9] = new SqlParameter("#CreatedBy", SqlDbType.Int, 10);
param[0].Value = VendorName;
param[1].Value = VendorBU;
param[2].Value = MDFAmount;
param[3].Value = StartDate;
param[4].Value = EndDate;
param[5].Value = VendorQuarter;
param[6].Value = MDFName;
param[7].Value = MDFSummary;
param[8].Value = Status;
param[9].Value = CreatedBy;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
//ClientScript.RegisterStartupScript(this.GetType(), "scriptid", window.parent.location.href='ViewVendors.aspx'", true);
Response.Write("<script>window.parent.location = 'ProposalListView.aspx';</script>");
//Response.Redirect("ProposalListView.aspx");
//Response.Write("<script>this.dialog('close');</script>");
}
}
public static void ClearControls(Control Parent){
if (Parent is TextBox)
{ (Parent as TextBox).Text = string.Empty; }
else
{
foreach (Control c in Parent.Controls)
ClearControls(c);
}
}
public string FormatDateNoTime(string input)
{
string thedate;
DateTime strDate = DateTime.Parse(input);
thedate = strDate.ToString("MM/dd/yyyy");
return thedate;
}
}
You can also use the DataBound event:
protected void FormView1_DataBound(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Insert)
{
var textBox = (TextBox) FormView1.FindControl("MyTextBox");
textBox.Text = "Default Value";
}
}
this is my button click code which fills the grid view
protected void Btnok_Click(object sender, EventArgs e)
{
try
{
if (Page.IsValid)
{
int passoutYear = Convert.ToInt32(passout.SelectedValue);
int courseList = Convert.ToInt32(course.SelectedValue);
StringBuilder sb = new StringBuilder();
string sep = "";
foreach (ListItem li in Branch.Items)
{
if (li.Selected)
{
sb.Append(sep + li.Value);
sep = ",";
}
}
DataTable dt = placedStudentManager.GetPlacedStudentList(sb, passoutYear, courseList);
if (dt != null && dt.Rows.Count != 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
Btnsave.Visible = true;
ViewState["dt"] = dt;
}
else
{
noRecordExistOnOkButton.Text = "No Record Exist To Be Inserted For Recruited Students";
Btnsave.Visible = false;
GridView1.Visible = false;
}
}
}
catch (Exception ex)
{
COMMON.logger.Error("Error On Button Btnok_Click:CompanySelected.aspx.cs ", ex);
}
}
this is my button save which save the checked check box gridRow in data base
protected void Btnsave_Click(object sender, EventArgs e)
{
try
{
if (Page.IsValid)
{
int passoutYear = Convert.ToInt32(passout.SelectedValue);
int companyId = Convert.ToInt32(company.SelectedValue);
int courseId = Convert.ToInt32(course.SelectedValue);
string package = txtpackage.Text.Trim();
string venu = txtvenue.Text.Trim();
DateTimeFormatInfo dateInfo = new DateTimeFormatInfo();
dateInfo.ShortDatePattern = "dd/MM/yyyy";
DateTime date = Convert.ToDateTime(vistDate.Text.Trim(), dateInfo);
DataTable gridviewTbl = new DataTable();
DataColumn dc1 = new DataColumn("company_id");
DataColumn dc2 = new DataColumn("course_id");
DataColumn dc3 = new DataColumn("branch_id");
DataColumn dc4 = new DataColumn("student_enrollment");
DataColumn dc5 = new DataColumn("company_visit_date");
DataColumn dc6 = new DataColumn("venu");
DataColumn dc7 = new DataColumn("package");
DataColumn dc8 = new DataColumn("passout_year");
gridviewTbl.Columns.Add(dc1);
gridviewTbl.Columns.Add(dc2);
gridviewTbl.Columns.Add(dc3);
gridviewTbl.Columns.Add(dc4);
gridviewTbl.Columns.Add(dc5);
gridviewTbl.Columns.Add(dc6);
gridviewTbl.Columns.Add(dc7);
gridviewTbl.Columns.Add(dc8);
if (GridView1 != null && GridView1.Rows.Count != 0)
{
int rowCount = GridView1.Rows.Count;
int i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("Chek");
if (cb != null && cb.Checked)
{
string enrollmetNo = GridView1.Rows[i].Cells[1].Text.ToString();
int branchId = Convert.ToInt32(GridView1.DataKeys[0].Value);
gridviewTbl.Rows.Add(companyId, courseId, branchId, enrollmetNo, date, venu, package, passoutYear);
}
i++;
}
if (gridviewTbl.Rows.Count != 0)
{
Boolean b = placedStudentManager.SaveSelectdStudent(gridviewTbl);
gridNotExist.Text = "Records Successfully inserted";
}
else
{
gridNotExist.Text = "Please check the record to be inserted";
Btnsave.Visible = true;
GridView1.Visible = true;
}
}
else
{
gridNotExist.Text = "Please Select The Recruited Student, so click the ok button first ";
}
}
else
{
GridView1.Visible = true;
Btnsave.Visible = true;
}
}
catch (Exception ex)
{
COMMON.logger.Error("Error On Button Btnsave_Click:CompanySelected.aspx.cs ", ex);
}
}
now i am doing paging using following code
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = (DataTable)ViewState["dt"];
GridView1.DataBind();
GridView1.Visible = true;
Btnsave.Visible = true;
// StringBuilder str=(StringBuilder)ViewState["chk"];
//foreach (GridViewRow row in GridView1.Rows)
//{
//}
}
following is the grid view
<%# Page Language="C#" MasterPageFile="~/Master Pages/AdminMaster.master" AutoEventWireup="true"
CodeFile="CompanySelected.aspx.cs" Inherits="Admin_CompanySelected" Trace="false" Title="Untitled Page" EnableEventValidation="false" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cph1" runat="Server">
<script language="javascript" type="text/javascript">
function BranchCheckBoxCheck(source, args)
{
var chkBoxListId=document.getElementById ('<%=Branch.ClientID%>');
var chkList=chkBoxListId.getElementsByTagName("input");
for(var i=0;i<chkList.length;i++)
{
if(chkList[i].checked)
{
args.IsValid = true;
return;
}
}
args.IsValid = false;
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphMain" runat="Server">
<div border="1">
<table id="TABLE1" onclick="return TABLE1_onclick()" align="center">
<tr>
<td style="height: 24px">
Passout Year*</td>
<td style="height: 24px">
<asp:DropDownList ID="passout" runat="server">
</asp:DropDownList>
<asp:CustomValidator ID="validateYearForSaveButton" runat="server" ControlToValidate="passout"
ErrorMessage="insert passout year" OnServerValidate="validateYearForSaveButton_ServerValidate"
ValidationGroup="save"></asp:CustomValidator></td>
<td style="height: 24px">
<asp:CustomValidator ID="passoutYearRequire" runat="server" ErrorMessage="Passout Year is Compulsory" ControlToValidate="passout" ValidationGroup="verify" OnServerValidate="passoutYearRequire_ServerValidate">
</asp:CustomValidator>
</td>
<td style="width: 101px; height: 24px;">
</td>
<td style="width: 126px; height: 24px">
</td>
<td style="height: 24px">
</td>
<td style="height: 24px">
</td>
</tr>
<tr>
<td>
Company Name*</td>
<td>
<asp:DropDownList ID="company" runat="server">
</asp:DropDownList>
</td>
<td>
<asp:CustomValidator ID="selectComapnyForSaveButton" runat="server" ControlToValidate="company"
ErrorMessage="Select A Company" OnServerValidate="selectComapnyForSaveButton_ServerValidate"
ValidationGroup="save"></asp:CustomValidator></td>
<td style="width: 101px">
Package*</td>
<td style="width: 126px">
<asp:TextBox ID="txtpackage" runat="server" Width="197px"></asp:TextBox></td>
<td>
<asp:RequiredFieldValidator ControlToValidate="txtpackage" ValidationGroup="save" ID="packageRequire" runat="server" ErrorMessage="Package Require"></asp:RequiredFieldValidator>
</td>
<td>
<asp:Button ID="Btnok" runat="server" Text="Ok" Width="43px" OnClick="Btnok_Click" ValidationGroup="verify" /></td>
</tr>
<tr>
<td>
Course*</td>
<td>
<asp:UpdatePanel id="update" runat="server">
<contenttemplate>
<asp:DropDownList ID="course" runat="server" AutoPostBack="True" OnSelectedIndexChanged="course_SelectedIndexChanged">
</asp:DropDownList>
</contenttemplate>
</asp:UpdatePanel><asp:CustomValidator ID="coursenecessaryForSaveButton" runat="server"
ControlToValidate="course" ErrorMessage="Select A Course" OnServerValidate="coursenecessaryForSaveButton_ServerValidate"
ValidationGroup="save"></asp:CustomValidator></td>
<td>
<asp:CustomValidator ID="courseNecessary" runat="server" ErrorMessage="Select A Course"
OnServerValidate="courseNecessary_ServerValidate" ValidationGroup="verify"></asp:CustomValidator></td>
<td style="width: 101px">
Branch Name*</td>
<td style="width: 126px">
<asp:UpdatePanel id="upchak" runat="server">
<contenttemplate>
<asp:CheckBoxList id="Branch" runat="server" OnSelectedIndexChanged="Branch_SelectedIndexChanged">
</asp:CheckBoxList>
</contenttemplate>
</asp:UpdatePanel>
</td>
<td>
<asp:CustomValidator id="branchRequire" runat="server" ValidationGroup="verify" ClientValidationFunction="BranchCheckBoxCheck" ErrorMessage="Select A Branch"></asp:CustomValidator>
<asp:CustomValidator id="branchrequireForSaveButton" runat="server" ValidationGroup="save" ClientValidationFunction="BranchCheckBoxCheck" ErrorMessage="Select A Branch"></asp:CustomValidator>
<%-- <asp:CustomValidator ID="branchNotexist" runat="server" ErrorMessage="No Branch Exist" ValidationGroup="verify" ControlToValidate="Branch" OnServerValidate="branchNotexist_ServerValidate"></asp:CustomValidator>--%>
</td>
<td>
<asp:Button ValidationGroup="save" ID="Btnsave" runat="server" Text="Save" OnClick="Btnsave_Click" />
</td>
</tr>
<tr>
<td>
Company Visit Date*</td>
<td>
<asp:TextBox ID="vistDate" runat="server" ></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="dateForSaveButton" runat="server" ControlToValidate="vistDate"
ErrorMessage="Visit Date Require" ValidationGroup="save"></asp:RequiredFieldValidator></td>
<td style="width: 101px">
</td>
<td style="width: 126px">
<asp:Label ID="noRecordExistOnOkButton" runat="server" Text="Label" Width="178px"></asp:Label></td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
Venue*
</td>
<td>
<asp:TextBox ID="txtvenue" runat="server"></asp:TextBox>
</td>
<td colspan="4">
<asp:RequiredFieldValidator ID="venRequire" runat="server" ControlToValidate="txtvenue"
ErrorMessage="Insert venu" ValidationGroup="save" Width="73px"></asp:RequiredFieldValidator>
<asp:Label ID="gridNotExist" ForeColor="Red" runat="server" Width="439px"></asp:Label></td>
<td>
</td>
</tr>
<tr>
<td colspan="5" style="height: 16px">
</td>
</tr>
<tr>
<td colspan="5">
<asp:GridView id="GridView1" AllowSorting="true" EnableViewState="true" AutoGenerateColumns="false" runat="server" AllowPaging="True" DataKeyNames="branch_id, default_check, student_id" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="2">
<Columns>
<asp:TemplateField HeaderText="Select Student">
<ItemTemplate>
<asp:CheckBox id="Chek" runat="server" Text="select" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Enrollment No." DataField="enrollment_no" />
<asp:BoundField HeaderText="Course Name" DataField="course_name"/>
<asp:BoundField HeaderText="Branch Name" DataField="branch_name"/>
<asp:BoundField HeaderText="Email Id" DataField="email" />
<asp:BoundField HeaderText="Mobile" DataField="mobile"/>
<asp:BoundField HeaderText="Name" DataField="first_name"/>
<asp:BoundField HeaderText="Surname" DataField="last_name" />
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</asp:Content>
now i want to do paging without loosing check box state and want to save the selectd check box row in data base on save button click how to achieve this please let me know .
I am using dot net framework 2.0...
#PhilPursglove :- My solution is like this
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{ Response.Write(GridView1.PageIndex.ToString());
int d = GridView1.PageCount; bool[] values = new bool[GridView1.PageSize];
CheckBox chb;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
chb = (CheckBox)GridView1.Rows[i].FindControl("Chek");
if (chb != null)
{
values[i] = chb.Checked;
}
}
Session["page" + GridView1.PageIndex] = values;
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = (DataTable)ViewState["dt"];
GridView1.DataBind(); GridView1.Visible = true; Btnsave.Visible = true;
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
if (Session["page" + GridView1.PageIndex] != null)
{ CheckBox chb; bool[] values = (bool[])Session["page" + GridView1.PageIndex];
for (int i = 0; i < GridView1.Rows.Count; i++)
{ chb = (CheckBox)GridView1.Rows[i].FindControl("Chek");
chb.Checked = values[i];
}
}
}
now i want on save button to store those selected chkbox row values to database
First of all, let me restate the problem as I understand it. You have a paged Gridview that has checkboxes on it. You select some of the checkboxes, then move to a different page. When you come back to the original page, you want those checkboxes to still be checked.
There are two elements to doing this, saving the CheckBox state on the old page, and then setting the Checkbox state on the new page.
Saving the CheckBox state on the old page
For every row in the gridview, we need to examine the checkbox to see if it's checked. If it is checked, we record the data id (from DataKeys) into a List. If it isn't checked but it was previously, we remove that id from the list. After we've done this for every row, we save the list in Viewstate.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
List<int> selectedList;
selectedList = (List<int>)this.ViewState["selectedList"];
if (selectedList == null)
{
selectedList = new List<int>();
}
foreach (GridViewRow row in Gridview1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox rowCheckBox;
int rowId;
// Get the Id
rowId = (int)Gridview1.DataKeys[row.RowIndex].Value;
// Get the CheckBox
rowCheckBox = (CheckBox)row.FindControl("Chek");
if (rowCheckBox.Checked)
{
// Don't add the id if it's already in the list
if (selectedList.Contains(rowId))
{ }
else
{
selectedList.Add(rowId);
}
}
else
{
// Remove the id if it was there but now we've unchecked the box
if (selectedList.Contains(rowId))
{
selectedList.Remove(rowId);
}
}
}
}
// Save the list into viewstate
this.ViewState["selectedList"] = selectedList;
// Do the paging as normal
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = (DataTable)ViewState["dt"];
GridView1.DataBind();
GridView1.Visible = true;
Btnsave.Visible = true;
}
Setting the CheckBox state on the new page
Now we're in a new page, as we databind each row we need to examine whether the Checkbox needs to be checked. To do this we will get the list out of Viewstate and as we bind each row we look to see if the key for the row is present in the list - if it is, we check the Checkbox. First off we need to attach this method to the Gridview:
<asp:GridView id="GridView1" OnRowDataBound="Gridview1_RowDataBound"
...
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
List<int> selectedList;
int rowId;
CheckBox rowCheckBox;
if (e.Row.RowType == DataControlRowType.DataRow)
{
selectedList = (List<int>)this.ViewState["selectedList"];
if (selectedList == null)
{ }
else
{
rowCheckBox = (CheckBox)e.Row.FindControl("Chek");
// Get the id for the row
rowId = (int)Gridview1.DataKeys[e.Row.RowIndex].Value;
// If the row Id is in the list then check the CheckBox
if (selectedList.Contains(rowId))
{
rowCheckBox.Checked = true;
}
}
}
}
You should now be able to move between pages and your checkboxes will be persistent :-)
At the point where you click your Save button, I would guess that you want to remove the List from Viewstate (this.ViewState.Remove("selectedList")) so that you reset everything. The only other thing that youneed to be aware of here is that my demo code here is based on using a single field in DataKeyNames for the Gridview whereas you're using three fields, so you'll probably want to pick just one field to use for the list - I suspect studentId will do what you want e.g.
rowId = (int)Gridview1.DataKeys(row.RowIndex).Values["studentId"];
When you click your Save button, you need to get the list out of viewstate again, add any checked rows into it from the current page, and then use that to generate your datatable to pass to your manager object.
protected void Btnsave_Click(object sender, EventArgs e)
{
List<int> selectedList;
selectedList = (List<int>)this.ViewState["selectedList"];
if (selectedList == null)
{
selectedList = new List<int>();
}
foreach (GridViewRow row in Gridview1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox rowCheckBox;
int rowId;
// Get the Id
rowId = (int)Gridview1.DataKeys[row.RowIndex].Value;
// Get the CheckBox
rowCheckBox = (CheckBox)row.FindControl("Chek");
if (rowCheckBox.Checked)
{
// Don't add the id if it's already in the list
if (selectedList.Contains(rowId))
{ }
else
{
selectedList.Add(rowId);
}
}
else
{
// Remove the id if it was there but now we've unchecked the box
if (selectedList.Contains(rowId))
{
selectedList.Remove(rowId);
}
}
}
}
int passoutYear = Convert.ToInt32(passout.SelectedValue);
int companyId = Convert.ToInt32(company.SelectedValue);
int courseId = Convert.ToInt32(course.SelectedValue);
string package = txtpackage.Text.Trim();
string venu = txtvenue.Text.Trim();
DateTimeFormatInfo dateInfo = new DateTimeFormatInfo();
dateInfo.ShortDatePattern = "dd/MM/yyyy";
DateTime date = Convert.ToDateTime(vistDate.Text.Trim(), dateInfo);
DataTable gridviewTbl = new DataTable();
...
foreach (int id in selectedList)
{
DataRow newStudentRow;
newStudentRow = gridviewTbl.NewRow;
newStudentRow[0] = id;
newStudentRow[1] = courseid;
...
gridviewTbl.Rows.Add(newStudentRow);
}
if (gridviewTbl.Rows.Count != 0)
{
Boolean b = placedStudentManager.SaveSelectdStudent(gridviewTbl);
if (b)
{
gridNotExist.Text = "Records Successfully inserted";
}
}
else
{
gridNotExist.Text = "Please check the record to be inserted";
Btnsave.Visible = true;
GridView1.Visible = true;
}
}