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();
Related
I am new to asp.net and i want to add new row in a gridview on button click... see my code kindly help me..its been 2 days i am working on it but didn't find the solution....
HTML CODE
<div>
<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false"
DataKeyNames="PRODUCTID" CellPadding="3" GridLines="Both" OnRowEditing="gridOnRowEditing"
OnRowCancelingEdit="gridOnRowCancelingEdit" OnRowUpdating="gridOnRowUpdating">
<HeaderStyle BackColor="Cyan" ForeColor="White" BorderColor="Red" />
<Columns>
<asp:CommandField ButtonType="Button" ShowCancelButton="true" ShowEditButton="true"
HeaderText="Edit & Update" />
<asp:BoundField DataField="PRODUCTID" HeaderText="PRODUCT ID" ReadOnly="true" />
<asp:TemplateField HeaderText="PRODUCT NAME">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtProduct1" Text='<%# Eval("PRODUCTNAME") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtProduct" Text='<%# Eval("PRODUCTNAME") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UNIT PRICE">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtPrice1" Text='<%# Eval("UNITPRICE") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtPrice" Text='<%# Eval("UNITPRICE") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button runat="server" OnClick="button1_click" ID="button1" Text="Add New Row" />
<%-- <input type="button" id="btnNew" value="Add New" onclick="addNew()" />--%>
</div>
C SHARP CODE
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=practice;Integrated Security=true;");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
protected void BindData()
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From PRODUCTDETAILS order by PRODUCTID asc", con);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
ViewState["CurrentTable"] = dt;
}
protected void gridOnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void gridOnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void gridOnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox txtProductName = (TextBox)row.FindControl("txtProduct");
TextBox UNITPRICE = (TextBox)row.FindControl("txtPrice");
string ProductName = txtProductName.Text;
string txtUnitPrice = UNITPRICE.Text;
int ProductID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
UpdateRecord(ProductID, ProductName, txtUnitPrice);
}
protected void UpdateRecord(int ProductID, string ProductName, string UnitPrice)
{
try
{
SqlCommand cmd = new SqlCommand("Update PRODUCTDETAILS set ProductName=#ProductName,UnitPrice=#UnitPrice WHERE ProductID=#ProductID", con);
cmd.Parameters.Add(new SqlParameter("#ProductID", ProductID));
cmd.Parameters.Add(new SqlParameter("#ProductName", ProductName));
cmd.Parameters.Add(new SqlParameter("#UnitPrice", UnitPrice));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
}
catch (Exception ex)
{
throw ex;
}
}
protected void AddNewRow()
{
//dt = new DataTable();
//DataRow dr = null;
//dt.Columns.Add(new DataColumn("PRODUCTID", typeof(string)));
//dt.Columns.Add(new DataColumn("PRODUCTNAME", typeof(string)));
//dt.Columns.Add(new DataColumn("UNITPRICE", typeof(string)));
//dr = dt.NewRow();
//dr["PRODUCTID"] = 14;
//dr["PRODUCTNAME"] = string.Empty;
//dr["UNITPRICE"] = string.Empty;
//dt.Rows.Add(dr);
//ViewState["CurrentTable"] = dt;
//GridView1.DataSource = dt;
//GridView1.DataBind();
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
int ProductID = Convert.ToInt32(GridView1.DataKeys[rowIndex].Value);
TextBox TextBoxName = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtProduct1");
TextBox TextBoxPrice = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtPrice1");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["PRODUCTID"] = ProductID + 1;
drCurrentRow["PRODUCTNAME"] = TextBoxName.Text;
drCurrentRow["UNITPRICE"] = TextBoxPrice.Text;
//dtCurrentTable.Rows[13 - 1]["PRODUCTID"] = ProductID + 1;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
}
protected void button1_click(object sender, EventArgs e)
{
AddNewRow();
}
}
}
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 want to display,insert,update,delete in DataGrid (Asp.net and Sqlserver2008) and then i want to export data from datagrid to excel file.
Table Structure
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>'A'</title>
<style type="text`/css">`
.Gridview
{
font-family: Verdana;
font-size: 10pt;
font-weight: normal;
color: black;
}
</style>
<script type="text/javascript">
function ConfirmationBox(username) {
var result = confirm('Are you sure you want to delete ' + username + ' Details?');
if (result) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId,UserName" runat="server" AutoGenerateColumns="false"
CssClass="Gridview" HeaderStyle-BackColor="#61A6F8" ShowFooter="true" HeaderStyle-Font-Bold="true"
HeaderStyle-ForeColor="White" OnRowCancelingEdit="gvDetails_RowCancelingEdit"
OnRowDeleting="gvDetails_RowDeleting" OnRowEditing="gvDetails_RowEditing"
OnRowUpdating="gvDetails_RowUpdating"
OnRowCommand="gvDetails_RowCommand" Height="275px" Width="530px">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server"
ImageUrl="~/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel"
ImageUrl="~/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server"
ImageUrl="~/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" runat="server"
ImageUrl="~/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.jpg"
CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<EditItemTemplate>
<asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrusrname" runat="server" />
<asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname"
Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrcity" runat="server" />
<asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="txtftrcity"
Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<EditItemTemplate>
<asp:TextBox ID="txtstate" runat="server" Text='<%#Eval("Designation") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblstate" runat="server" Text='<%#Eval("Designation") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrDesignation" runat="server" />
<asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation"
Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#61A6F8" Font-Bold="True" ForeColor="White"></HeaderStyle>
</asp:GridView>
</div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
<div>
<asp:Button ID="btn_Excel" runat="server" Text="Excel"
onclick="btn_Excel_Click" />
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Reflection;
using System.IO;
using System.Collections;
public partial class _Default : System.Web.UI.Page
{
private SqlConnection con = new SqlConnection("Data Source=.;uid=sa;pwd=sa123;database=Example1");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtstate");
con.Open();
SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "' where UserId=" + userid, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = username + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" + userid, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Blue;
lblresult.Text = username + " details deleted successfully";
}
}
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//getting username from particular row
string username = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "UserName"));
//identifying the control in gridview
ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
//raising javascript confirmationbox whenver user clicks on link button
if (lnkbtnresult != null)
{
lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + username + "')");
}
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
TextBox txtDesgnation = (TextBox)gvDetails.FooterRow.FindControl("txtftrDesignation");
con.Open();
SqlCommand cmd =
new SqlCommand("insert into Employee_Details(UserName,City,Designation) values('"
+ txtUsrname.Text + "','" + txtCity.Text + "','" + txtDesgnation.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Blue;
lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtUsrname.Text + " Details not inserted";
}
}
}
protected void btn_Excel_Click(object sender, EventArgs e)
{
this.gvDetails.AllowPaging = false;
this.gvDetails.AllowSorting = false;
this.gvDetails.EditIndex = -1;
this.BindEmployeeDetails();
Response.Clear();
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition", "attachment;filename=MyList.xls");
Response.Charset = "";
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
gvDetails.RenderControl(hwriter);
Response.Write(swriter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
//to Render Control
}
}
My code works fine.
But my excel file looks like this
Excel output
So i don't want the images in datagrid to be exported.
How can i do that.
Kindly reply.
Ok i got the solution (From a colleague).
Please vote my answer if its correct.
Explanation:
1.We have to first make a temporary table.
2.Now add only the required column from datagrid.
3.Use temporary table to Export data in Excel.
Code:In the Button click call the function ExportUsersDataTable
protected void btn_Excel_Click(object sender, EventArgs e){ExportUsersDataTable()}
The function definition is:
public void ExportUsersDataTable()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
string sFilename = "UserToRoleMapping.xls";
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = ""; //string.Empty;
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + sFilename + "\"");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
GridView gvTemp = new GridView();
//Temporary Table for changing the ExcelSheet Headers
DataTable dtTemp = new DataTable();
dtTemp.Columns.Add("User Id");
dtTemp.Columns.Add("User Name");
dtTemp.Columns.Add("City");
dtTemp.Columns.Add("Designation");
dtTemp.AcceptChanges();
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow dr = dtTemp.NewRow();
dr["User Id"] = ds.Tables[0].Rows[i]["UserId"].ToString();
dr["User Name"] = ds.Tables[0].Rows[i]["UserName"].ToString();
dr["City"] = ds.Tables[0].Rows[i]["City"].ToString();
dr["Designation"] = ds.Tables[0].Rows[i]["Designation"].ToString();
dtTemp.Rows.Add(dr);
dtTemp.AcceptChanges();
}
}
if (dtTemp.Rows.Count > 0)
{
gvTemp.DataSource = dtTemp;
gvTemp.DataBind();
gvTemp.RenderControl(htw);
response.Write(sw.ToString());
}
response.End();
}
}
}
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";
}
}
I have problem on page bellow, in gdvCar_DataBound I add three buttons, when I click on any of them, page go to postback but doesn't enter in gdvCar_RowCommand and then that buttons ( and images that I also add in gdvCar_DataBound) disaper. Grid is then full like gdvCar_DataBound isn't execute. My question is why it doesn't enter at gdvCar_RowCommand ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HMS.library;
using System.Data.SqlClient;
namespace HMS
{
public partial class Cars : System.Web.UI.Page
{
#region fields
private const Int16 PageId = 1;
private String connectionString = "Server=localhost;Database=hms_test;Trusted_Connection=True;";
String[] filters = null;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillProducer();
FillModel(Convert.ToInt16(ddlProducer.SelectedValue));
RestoreFilters();
FillGrid();
}
}
#region events
protected void ddlProducer_Changed(object sender, EventArgs e)
{
if (ddlProducer.SelectedValue != "0")
{
ddlModel.Enabled = true;
FillModel(Convert.ToInt16(ddlProducer.SelectedValue));
}
else
{
ddlModel.SelectedValue = "0";
ddlModel.Enabled = false;
}
upSearch.Update();
}
protected void gdvCar_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Reserve":
{
pnlReserve.Visible = true;
break;
}
case "Phone":
{
break;
}
case "Email":
{
break;
}
}
}
protected void gdvCar_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String id = e.Row.Cells[0].Text;
Image img = new Image();
img.ID = "img_one" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[7].Text;
e.Row.Cells[7].Controls.Add(img);
img = new Image();
img.ID = "img_two" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[8].Text;
e.Row.Cells[8].Controls.Add(img);
img = new Image();
img.ID = "img_three" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[9].Text;
e.Row.Cells[9].Controls.Add(img);
ImageButton imbReserve = new ImageButton();
imbReserve.ID = "res" + id;
imbReserve.Enabled = true;
imbReserve.Width = 48; imbReserve.Height = 48;
imbReserve.ToolTip = "Reserve"; imbReserve.AlternateText = "Reserve";
imbReserve.ImageUrl = "images/icons/key.gif";
imbReserve.CommandName = "Reserve";
imbReserve.CommandArgument = id;
e.Row.Cells[10].Controls.Add(imbReserve);
ImageButton imbPhone = new ImageButton();
imbPhone.ID = "phone" + id;
imbPhone.Enabled = true;
imbPhone.Width = 48; imbPhone.Height = 48;
imbPhone.ToolTip = "Reserve by phone"; imbPhone.AlternateText = "Phone";
imbPhone.ImageUrl = "images/icons/phone.jpg";
imbPhone.CommandName = "Phone";
imbPhone.CommandArgument = id;
e.Row.Cells[11].Controls.Add(imbPhone);
ImageButton imbEmail = new ImageButton();
imbEmail.ID = "email" + id;
imbEmail.Enabled = true;
imbEmail.Width = 48; imbEmail.Height = 48;
imbEmail.ToolTip = "Reserve by email"; imbEmail.AlternateText = "Email";
imbEmail.ImageUrl = "images/icons/email.jpg";
imbEmail.CommandName = "Email";
imbEmail.CommandArgument = id;
e.Row.Cells[12].Controls.Add(imbEmail);
}
}
protected void imbSearch_Click(object sender, ImageClickEventArgs e)
{
StoreFilters();
FillGrid();
}
#endregion
#region functions
private void FillProducer()
{
hmsDataContext hms = new hmsDataContext();
var source = from o in hms.producer_cars
orderby o.name
select new
{
o.id,
o.name
};
foreach (var temp in source)
ddlProducer.Items.Add(new ListItem(temp.name, temp.id.ToString()));
ddlProducer.Items.Insert(0, (new ListItem("all producers", "0")));
}
private void FillModel(int producer_id)
{
hmsDataContext hms = new hmsDataContext();
var source = from o in hms.model_cars
from p in hms.producer_cars
where o.producer_car_id == producer_id && p.id == producer_id
orderby o.name
select new
{
o.id,
o.name
};
ddlModel.Items.Clear();
foreach (var temp in source)
ddlModel.Items.Add(new ListItem(temp.name, temp.id.ToString()));
ddlModel.Items.Insert(0, (new ListItem("all producers", "0")));
}
private void FillGrid()
{
SqlConnection conn = new SqlConnection(connectionString);
String command = #"SELECT car.id AS id, car.price as price, car.weight as weight,
car.year as year, producer_car.name as producer, model_car.name as model, car.number_seats as number_seats, car.photo_one as photo_one,car.photo_two as photo_two,car.photo_three as photo_three, '' as reserver,'' as phone,'' as email
FROM car INNER JOIN model_car on car.model_car_id=model_car.id
INNER JOIN producer_car on model_car.producer_car_id=producer_car.id";
if(filters!=null){
String[] search=new String[5];
search[0]=filters[0]!="0"?"producer_car.id="+filters[0]:"";
search[1]= filters[1] != "0" ? "model_car.id=" + filters[1] : "";
search[2]=filters[2]!=""?"car.color LIKE \'"+filters[2]+"\'":"";
search[3]=filters[3]!=""?"car.price<"+filters[3]:"";
search[4] = filters[4] != "" ? "car.number_seats=" + filters[4] : "";
var a=from f in search
where f!=""
select f;
String filterAddition="";
if(a.Count()>0){
filterAddition=" WHERE ";
foreach ( var b in a){
filterAddition+=" "+b+" AND";
}
filterAddition=filterAddition.EndsWith("AND")?filterAddition.Substring(0,filterAddition.Length-3):filterAddition;
}
command+=filterAddition;
}
SqlCommand comm = new SqlCommand(command, conn);
SqlDataReader r = null;
try
{
comm.Connection.Open();
r =comm.ExecuteReader();
gdvCar.DataSource = r;
gdvCar.DataBind();
r.Close();
}
catch (Exception exc)
{
throw (exc);
}
finally
{
conn.Close();
}
}
private void StoreFilters()
{
filters = new String[5];
filters[0] = ddlProducer.SelectedValue;
filters[1] = ddlModel.SelectedValue;
filters[2] = ddlColor.SelectedValue;
filters[3] = txtStartPrice.Text;
filters[4] = ddlNumber.SelectedValue;
Session["1"] = filters;
}
private void RestoreFilters()
{
if (Session["1"] != null)
{
filters = (String[])Session["1"];
ddlProducer.SelectedValue = filters[0];
ddlProducer_Changed(null, null);
ddlModel.SelectedValue = filters[1];
ddlColor.SelectedValue = filters[2];
txtStartPrice.Text = filters[3];
ddlNumber.SelectedValue = filters[4];
}
}
private void ReserveCar(String FirstName, String LastName, DateTime Start, DateTime End, String Visa, Int16 CarId)
{
hmsDataContext hms = new hmsDataContext();
var a = from c in hms.cars
from rc in hms.rented_cars
where c.id == rc.id_car && c.id == CarId
select new
{
start = rc.start,
end = rc.end
};
Boolean free = false;
if (a.Count() == 0)
{
free = true;
}
else if (a.Count() == 1)
{
if ((a.First().start > End) || (a.First().end < Start))
free = true;
}
else
{
if ((a.First().start > End) || (a.First().end < Start))
free = true;
else if(!free)
{
int n = a.Count();
for (int i = 0; (i < n - 1) && (!free); i++)
{
if (a.ElementAt(i).end < Start && a.ElementAt(i + 1).start > End)
free = true;
i++;
}
if (!free)
{
if (a.ElementAt(n - 1).end < Start)
free = true;
}
}
}
if (free)
{
//insert
}
else
{
//label-nije slobodno za taj termin
}
}
#endregion
}
}
aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Cars.aspx.cs" Inherits="HMS.Cars"
MasterPageFile="~/frame.Master" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ContentPlaceHolderID="content" ID="con" runat="server">
<link rel="StyleSheet" href="css/menu.css" type="text/css" media="all">
<asp:ScriptManager ID="sc" runat="server">
</asp:ScriptManager>
<div id="menu">
<ul class="glossymenu">
<li><b>Home</b></li>
<li class="current"><b>Cars</b></li>
<li><b>Boats</b></li>
<li><b>Contact</b></li>
<li><b>Admin</b></li>
</ul>
</div>
<div>
<div>
<asp:UpdatePanel ID="upSearch" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="search">
<fieldset>
<legend>Advanced search</legend>
<table>
<tr>
<td>
Proizvođač:<asp:DropDownList ID="ddlProducer" runat="server" OnSelectedIndexChanged="ddlProducer_Changed"
AutoPostBack="true">
</asp:DropDownList>
</td>
<td>
Model:<asp:DropDownList ID="ddlModel" runat="server" Enabled="false">
</asp:DropDownList>
</td>
<td>
Boja:<asp:DropDownList ID="ddlColor" runat="server">
<asp:ListItem Text="all" Value=""></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
Cena do:
<asp:TextBox ID="txtStartPrice" runat="server" MaxLength="10"></asp:TextBox>
din/dan
</td>
<td>
Number seats:<asp:DropDownList ID="ddlNumber" runat="server">
<asp:ListItem Text="-- --" Value=""></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
<asp:ListItem Text="4" Value="4"></asp:ListItem>
<asp:ListItem Text="5" Value="1"></asp:ListItem>
<asp:ListItem Text="6" Value="2"></asp:ListItem>
<asp:ListItem Text="7" Value="3"></asp:ListItem>
<asp:ListItem Text="8" Value="4"></asp:ListItem>
<asp:ListItem Text="9" Value="2"></asp:ListItem>
<asp:ListItem Text="10" Value="3"></asp:ListItem>
<asp:ListItem Text="11" Value="4"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:ImageButton ID="imbSearch" runat="server" ImageUrl="images/icons/search.png"
Width="32" Height="32" ToolTip="Search by choosen criterions" AlternateText="Search"
OnClick="imbSearch_Click" />
</td>
</tr>
</table>
</fieldset>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<br />
<div>
<asp:UpdatePanel ID="upGrid" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:GridView ID="gdvCar" runat="server" OnRowCommand="gdvCar_RowCommand"
OnRowDataBound="gdvCar_DataBound">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div>
<asp:UpdatePanel ID="upTemp" runat="server"><ContentTemplate>
<asp:Panel ID="pnlReserve" runat="server" Visible="false" Width="400" Height="400">
<asp:UpdatePanel ID="upReserve" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</ContentTemplate></asp:UpdatePanel>
</div>
</div>
</asp:Content>
You have to recreate the buttons in RowCreated on every Postback, otherwise their events won't fire.
Save what you need in RowDataBound in the ViewState. In the RowCreated recreate them on Postback(RowDatabound will only be called on Databinding) based on the Viewstate value. Then all controls are available in early page-lifecyle to raise their events.
I believe you can do it in a more elegant way, take a look,
<asp:GridView ...>
<Columns>
<asp:BoundField HeaderText="Some Caption" DataField="Column name from the DataReader result"/>
...
<asp:TemplateField HeaderText="Image..">
<asp:Image runat="server" ImageUrl='<%# String.Format("images/car/{0}", Eval("The column name from the DataReader of the cell 7") %>' />
</asp:TemplateField>
<asp:TemplateField HeaderText="ImageButton..">
<asp:ImageButton runat="server" .../>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then you don't have to add the buttons and the images in the code and takecare of adding them each time the row is created, you just need to fetch the data from the database and set the DataSource of the gridview, and I think you can also get rid of the code fetching the data and replace it with a SqlDataSource.
Take a look at this article about the GridView,
http://msdn.microsoft.com/en-us/library/aa479353.aspx