Pages

Saturday, December 18, 2010

Fileupload with file type check

0 comments

--------------------------------------
protected void btnUpload_Click(object sender, EventArgs e)
{
string path = Server.MapPath("upload/");
bool boolOk = false;

if (FUpload.HasFile)
{
string ext = String.Empty;
ext = System.IO.Path.GetExtension(FUpload.FileName).ToLower();

String[] allowed = { ".doc", ".pdf", ".txt" };
for (int i = 0; i <= allowed.Length - 1; i++)
{
if (ext == allowed[i])
{
boolOk = true;
}
if (boolOk == true)
{
try
{
FUpload.PostedFile.SaveAs(path + FUpload.FileName);
lblmsg.Text = "File uploaded successfully!!";
}
catch (Exception ex)
{
lblmsg.Text = ex.Message.ToString();
}

}
else
{
lblmsg.Text = "Only text files are supported. Please change!!";
}

}

Thursday, December 16, 2010

To delete all the TABLES, SPs, TRIGGERS, VIEWS from a Database

0 comments

JUST RUN THIS QUERY ON THE SELECTED DATABASE
-----------------------------------------------------




DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])

WHILE @name is not null
BEGIN
SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Procedure: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped View: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Function: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

WHILE @name is not null
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint IS NOT NULL
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT ' + RTRIM(@constraint)
EXEC (@SQL)
PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint is not null
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT ' + RTRIM(@constraint)
EXEC (@SQL)
PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Table: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO



Sunday, December 5, 2010

Handling Dropdown list inside Gridview with Autopostback

0 comments

----------------------------------------------------



Many a times there are circumstances where by we need to use dropdown list inside a Gridview and also handle the index changed event of the dropdown list. The easy example of this kind of requirement would be when we nee to fill another dropdown list in the same row from the value selected in the first dropdown list.

We all know that the dropdown list does not support command name property so you cannot handle the event in the row command event.
A simple solution to the problem is to use the namingcontainer in the selectedindexchanged event and get the reference of the parent row view. After that we can do what we want from the row view. Here is an example in the code.
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e) {
// get reference to the row
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
// Get the reference of this DropDownlist
DropDownList dropdownlist1 = (DropDownList) gvr.FindControl("dropdownlist1");
// Get the reference of other DropDownlist in the same row.
DropDownList ddlParagraph = (DropDownList) gvr.FindControl("ddlParagraph");
}



GridView1_SelectedIndexChanged_1

0 comments

SelectedIndexChanged
---------------------------------------------------------




protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = GridView1.SelectedRow.Cells[0].Text;
TextBox2.Text = GridView1.SelectedRow.Cells[1].Text;
TextBox3.Text = GridView1.SelectedRow.Cells[2].Text;
TextBox4.Text = GridView1.SelectedRow.Cells[3].Text;
}





Saturday, November 27, 2010

Dropdown list inside Gridview with Autopostback

0 comments

---------------------------------------------------------------------





Many a times there are circumstances where by we need to use dropdown list inside a Gridview and also handle the index changed event of the dropdown list. The easy example of this kind of requirement would be when we nee to fill another dropdown list in the same row from the value selected in the first dropdown list.

We all know that the dropdown list does not support command name property so you cannot handle the event in the row command event.
A simple solution to the problem is to use the namingcontainer in the selectedindexchanged event and get the reference of the parent row view. After that we can do what we want from the row view.

Here is an example in the code.

protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
// get reference to the row
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);

// Get the reference of this DropDownlist
DropDownList dropdownlist1 = (DropDownList) gvr.FindControl("dropdownlist1");


// Get the reference of other DropDownlist in the same row.
DropDownList ddlParagraph = (DropDownList) gvr.FindControl("ddlParagraph");
}





With BoundColumns

0 comments

------------------------------------------------------------




//WITH BOUND COLUMNS
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
// ValidateRequest=&quot;false&quot; in the page directive
// GridViewRow selectedRow = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;

if (e.CommandName.ToLower().Equals(&quot;select&quot;))
{
GridViewRow grow = (GridViewRow)((Button)e.CommandSource).NamingContainer;

int index = Convert.ToInt32(grow.RowIndex);

DropDownList myddl = (DropDownList)(grow.FindControl(&quot;ddlCountry&quot;));

TextBox1.Text = grow.Cells[1].Text;
TextBox2.Text = grow.Cells[2].Text;
TextBox3.Text = grow.Cells[3].Text;
TextBox4.Text = grow.Cells[4].Text;
TextBox5.Text = myddl.SelectedItem.Text;
}
}






Row_Command_2

0 comments

---------------------------------------------------------------




<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" CommandName="ViewFranchisee" CommandArgument='<%#Eval("Email") %>'
CssClass="tahomatext"><img src="../images/icon_details.png" style="border:0;" alt="Franchisee Details" title="Franchisee Details" /></asp:LinkButton>
</ItemTemplate>

protected void grdFranch_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "ViewFranchisee")
{
email = e.CommandArgument.ToString();
Response.Redirect("ViewFranchiseeProfile.aspx?email=" + email);
}
}





Row_Command_Edit_Update

0 comments

----------------------------------------------------------




<ItemTemplate>
<asp:Label ID="lblluserName" runat="server"
Text='<%#Eval("LastName")+","+Eval("FirstName") %> '></asp:Label>
</ItemTemplate>


<ItemTemplate>
<asp:Label ID="lblStatusTerritory" Text='<%#get(Convert.ToBoolean((Eval("IsActive"))))%>'
runat="server"></asp:Label>
</ItemTemplate>



<asp:TemplateField ItemStyle-Width="40px">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" CommandName="Edit" ImageUrl="~/images/edit1.png" ToolTip="Edit record. "
runat="server" Height="15" Width="15" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnupdate" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="btncancel" runat="server" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>

-----------------

protected void grdDirectory_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString().Equals("Update"))
{
DataTable dt = new DataTable();
Hashtable ht = new Hashtable();

LinkButton lnkupdate = (LinkButton)e.CommandSource;
GridViewRow grow = lnkupdate.NamingContainer as GridViewRow;

TextBox txtworkphone = (TextBox)grow.FindControl("txtworkphone");
string strWorkPhone = txtworkphone.Text.ToString().Trim(); ******

Label lblID = (Label)grow.FindControl("lblID");

TextBox txtCompany = (TextBox)grow.FindControl("txtCompany");
string strCompany = txtCompany.Text.ToString().Trim();
}
}

if (e.CommandName.ToString().Equals("Delete"))
{
DataTable dt = new DataTable();
Hashtable ht = new Hashtable();

//LinkButton lnkDelete = (LinkButton)e.CommandSource;
ImageButton imgDelete = (ImageButton)e.CommandSource;
GridViewRow grow = imgDelete.NamingContainer as GridViewRow;

// TextBox txtworkphone = (TextBox)grow.FindControl("txtworkphone");
Label lblID = (Label)grow.FindControl("lblID");

ht.Add("@id", lblID.Text);








0 comments

-------------------------------------------------------------------



protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "UnitPrice"));

if (index <= 30)
{
// e.Row.ForeColor = System.Drawing.Color.Red; // whole row will be red
e.Row.Cells[4].ForeColor = System.Drawing.Color.Red; // only the unitprice cell will be red.
}
}
else
{

}
}




DropdownList in ItemTemplate having the item preselected

0 comments

-------------------------------------------------------------


############################################################

<asp:GridView ID="grdData" DataKeyNames="userid,categoryname">


protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList _ddlcategory = (DropDownList)e.Row.FindControl("ddlcategory");
if (_ddlcategory != null)
{
_ddlcategory.DataSource = GetCategory();
_ddlcategory.DataTextField = "categoryname";
_ddlcategory.DataValueField = "categoryname";
_ddlcategory.DataBind();

_ddlcategory.SelectedItem.Text = grdData.DataKeys[e.Row.RowIndex].Values[1].ToString();


}

}

}



public DataTable GetCategory()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["conPractice"].ToString();

SqlDataAdapter adp = new SqlDataAdapter("GetCategory", con);
adp.Fill(dt);

return dt;

}

############################################


Pager row format [ ]

0 comments

---------------------------------------------------------------------------


1.



protected void grdProject_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
TableCell tc = new TableCell();
TableCell tc1 = new TableCell();

tc.Text = "[Page:";
tc1.Text = "]";
Table tbl = new Table();
tbl = (Table)(e.Row.Cells[0].Controls[0]);
tbl.Rows[0].Cells.AddAt(grdProject.PageIndex, tc);
tbl.Rows[0].Cells.AddAt(grdProject.PageIndex + 2,tc1);
}


}

##########################################################

2.


<asp:GridView ID="grid1" runat="server" AutoGenerateColumns="false"
DataKeyNames="ProductId,Category">


public void grid1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlCategory = (DropDownList)e.Row.FindControl("ddlCategory");
if (ddlCategory != null)
{
ddlCategory.DataSource = Product.FetchCategory();
ddlCategory.DataBind();
ddlCategory.SelectedValue =
grid1.DataKeys[e.Row.RowIndex].Values[1].ToString();

// using DatakeyNames property
}
}

if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlCategoryInput = (DropDownList)e.Row.FindControl(
"ddlCategoryInput");
ddlCategoryInput.DataSource = Product.FetchCategory();
ddlCategoryInput.DataBind();
}
}



##########################################################



Total in Footer_Gridview

0 comments

------------------------------------------------------------


1.



protected void GridView1_DataBound(object sender, EventArgs e)
{
decimal valueInStock = 0;
foreach (GridViewRow row in GridView1.Rows)
{
decimal price = Decimal.Parse(row.Cells[2].Text.Substring(1));
int unitsInStock = Int32.Parse(row.Cells[3].Text);
valueInStock += price * unitsInStock;
}

GridViewRow footer = GridView1.FooterRow;

footer.Cells[0].ColumnSpan = 3;
footer.Cells[0].HorizontalAlign = HorizontalAlign.Center;

footer.Cells.RemoveAt(2);
footer.Cells.RemoveAt(1);

footer.Cells[0].Text = "Total value in stock (on this page): " + valueInStock.ToString("C");

}

}






Format Gridview with OnRowCreated function

0 comments

----------------------------------------------------------------------------------
1

if (e.Row.RowType == DataControlRowType.DataRow)
{
Comments = (String)DataBinder.Eval(e.Row.DataItem, "Comment");
if (Comments.Length > 30)
{
Comments = Comments.Substring(0, 40) +"...";
e.Row.ForeColor = System.Drawing.Color.Crimson;
e.Row.Font.Italic = true;
}
}

---------------------------------------------------------------------------------
2
protected void grdData_RowCreated(object sender, GridViewRowEventArgs e)
{

if ((e.Row.RowType == DataControlRowType.DataRow) && (e.Row.RowState == DataControlRowState.Selected))
{
string strCellvalue = DataBinder.Eval(e.Row.DataItem, "categoryname").ToString();
if (strCellvalue == "Admin")
{
e.Row.BackColor = System.Drawing.Color.LightPink;
}
}
}

#######################################################
3

<asp:GridView runat="server" ID="gridProducts" DataSourceID="productsSource"
AutoGenerateColumns="false" OnRowCreated="gridProducts_RowCreated">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="ProductNumber" HeaderText="Number" />
<asp:BoundField DataField="DaysToManufacture" HeaderText="Days To Manufacture" />
</Columns>
</asp:GridView>

protected void gridProducts_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int daysToManufacture = (int)DataBinder.Eval(e.Row.DataItem, "DaysToManufacture");

if (daysToManufacture == 0)
{
e.Row.BackColor = System.Drawing.Color.LightPink;
e.Row.ForeColor = System.Drawing.Color.Maroon;
}
else if (daysToManufacture == 1)
{
e.Row.BackColor = System.Drawing.Color.LightCyan;
e.Row.ForeColor = System.Drawing.Color.DarkBlue;
}
else
{
e.Row.BackColor = System.Drawing.Color.LightGray;
e.Row.ForeColor = System.Drawing.Color.Red;
}
}
}
####################################################


RowDeleting(1)

0 comments

---------------------------------------------------------------
1.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
TableCell cell = GridView1.Rows[e.RowIndex].Cells[2];
if (cell.Text == "Chai")
{
e.Cancel = true;
// lblmsg.Text = "You cannot delete : Chai";
ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('You cannot delete this product.');</script>");
}
else
{
Response.Write(" Product Deleted"); // write here the code to delete the product.
}
}
###########################################









Thursday, November 25, 2010

Sorting Gridview

0 comments



if (!IsPostBack)
{
ViewState["sortOrder"] = "";
bindGridView("", "");
}

------------------

public void bindGridView(string sortExp,string sortDir)
{
DataSet myDataSet = new DataSet();
myDataSet = NSBuilder.DataAccess.GetDataSet("Usp_GetAllProjects");

DataView myDataView = new DataView();
myDataView = myDataSet.Tables[0].DefaultView;

if (sortExp!=string.Empty)
{
myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
}

grdProjects.DataSource = myDataView;
grdProjects.DataBind();

}

--------------------


public string sortOrder
{
get
{
if (ViewState["sortOrder"].ToString() == "desc")
{
ViewState["sortOrder"] = "asc";
}
else
{
ViewState["sortOrder"] = "desc";
}
return ViewState["sortOrder"].ToString();
}
set
{
ViewState["sortOrder"] = value;
}
}


------------------

protected void grdProjects_Sorting(object sender, GridViewSortEventArgs e)
{
bindGridView(e.SortExpression, sortOrder);
// sortorder property used here.
}

protected void grdProjects_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdProjects.PageIndex = e.NewPageIndex;
bindGridView("","");
}

----------




Sunday, November 21, 2010

Pre-Selecting DropDownlist in EditItemTemplate-Gridview

0 comments

PRE SELECTING ITEMS IN DROPDOWNLIST IN GRIDVIEW EDIT MODE
---------------
<asp:TemplateField HeaderText="State">
<ItemTemplate>
<asp:Label ID="lblState" runat="server" Text='<%#Eval("TState") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlState" CssClass="textTableElement" AutoPostBack="true"

ToolTip='<%#Container.DataItemIndex%>' runat="server"

OnSelectedIndexChanged="ddlState_SelectedIndexChanged"> </asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
******************************

protected void grdData_RowEditing(object sender, GridViewEditEventArgs e)
{
grdData.EditIndex = e.NewEditIndex;
BindGrid();

GridViewRow grow = (GridViewRow)grdData.Rows[e.NewEditIndex];

DropDownList ddl = new DropDownList();
ddl = (DropDownList)grow.FindControl("ddlCat");
ddl.DataSource = GetCategory();
ddl.DataTextField = "categoryname";
ddl.DataValueField = "categoryid";
ddl.DataBind();

string str = ViewState["cat"].ToString();

ddl.Items.FindByText(str).Selected = true;

}
--------------------------------------------

protected void grdData_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "edit")
{
GridViewRow grow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
Int32 userid = Convert.ToInt32(e.CommandArgument.ToString());
ViewState["userid"] = userid;

Label lblCat = new Label();
lblCat = (Label)grow.FindControl("lblcategory");

ViewState["cat"] = lblCat.Text.ToString(); // used in row_editing event to preselect the previous item

}

//******************
if (e.CommandName == "update")
{
GridViewRow grow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

DropDownList ddl = (DropDownList)grow.FindControl("ddlCat");

ddl.DataSource = GetCategory(); // function returns a datatable
ddl.DataTextField = "categoryname";
ddl.DataValueField = "categoryid";
ddl.DataBind();

Int32 userid = Convert.ToInt32(ViewState["userid"]);
Int32 catid = Convert.ToInt32(ViewState["categoryid"]);
Int32 intresult;

SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["conPractice"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UpdateUser";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;


SqlParameter param = new SqlParameter();

cmd.Parameters.AddWithValue("@userid", userid);
cmd.Parameters.AddWithValue("@categoryid", catid);
param = cmd.Parameters.Add("ReturnValue", SqlDbType.Int);
param.Direction = ParameterDirection.ReturnValue;


con.Open();
cmd.ExecuteNonQuery();

intresult =(int) cmd.Parameters["ReturnValue"].Value;
con.Close();

if (intresult == 1)
{
lblmsg.Text="Updated Successfully!";

grdData.EditIndex = -1;
BindGrid();
}
if (intresult == -1)
{
lblmsg.Text = "Not Updated!!";
}
}
//******************
if (e.CommandName == "delete")
{

GridViewRow grow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
}
}

******************************

protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlState;
ddlState = (DropDownList)sender;

string state = ddlState.SelectedItem.Text;


ViewState["state"] = state;

DropDownList ddlCounty;
ddlCounty = (DropDownList)grdTerritory.Rows[Convert.ToInt32
(ddlState.ToolTip)].FindControl("ddlCounty");


clsBuilder.bind_County(ddlCounty, state);

}
**************************





Saturday, November 13, 2010

change status function

0 comments

----------------------------------------------------




<asp:TemplateField HeaderText="Change Status">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnIsactive" runat="server"
OnClick="change_status"
CommandArgument='<%#Eval("ID")+","+Eval("ProjectID") %>'
ToolTip='<%#Eval("UserName")%>'
Text='<%#get(Convert.ToBoolean((Eval("IsActive"))))%>'
></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
public string get(bool act)
{
if (act == true)
{
return "Deactivate";
}
else
{
return "Activate";
}
}
protected void change_status(object sender, EventArgs e)
{
if (Convert.ToInt32(Session["AccessRight"]) == 1)
{

lnk = ((LinkButton)(sender));
string[] array = lnk.CommandArgument.ToString().Split(',');
prjID = Convert.ToInt32(array[1].ToString());
Int32 bid = Convert.ToInt32(array[0].ToString());
Hashtable ht = new Hashtable();
ht.Clear();
userN = Convert.ToString(lnk.ToolTip);
ViewState["logincheck"] = userN;
string mal = getUserMail(userN);
string prtit = getProjectTitle(prjID);
ViewState["eMail"] = mal;
accountType = "bid on " + prtit;
ht.Add("@bid", bid);
ht.Add("@prjID", prjID);
if (lnk.Text == "Deactivate")
{
chk = "Activated";
ht.Add("@isactive", Convert.ToBoolean("False"));
NSBuilder.DataAccess.ExecuteNonQuery("sp_activeBidStatus", ht);
lnk.Text = "Activate";
mailStatus = "DeActivated";
lblmsg.Visible = true;
lblmsg.Text = userN + " bid is DeActivated.";
//sendMail();
chk = "";
string javaScript =
"<script language=JavaScript>\n" +
"alert('" + userN + " bid has been DeActivated. !!');\n" +
"</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", javaScript);
}
else
{
chk = "DeActivated";
ht.Add("@isactive", Convert.ToBoolean("True"));
NSBuilder.DataAccess.ExecuteNonQuery("sp_activeBidStatus", ht);
lnk.Text = "Deactivate";
mailStatus = "Activated";
lblmsg.Visible = true;

lblmsg.Text = userN + " bid is Activated.";
// sendMail();
chk = "";
string javaScript =
"<script language=JavaScript>\n" +
"alert('" + userN + " bid has been Activated. !!');\n" +
"</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", javaScript);
}
// searchMethod();
}










IMAGE TYPE VALIDATION IN FILE UPLOAD CONTROL

0 comments


IMAGE TYPE VALIDATION IN FILE UPLOAD CONTROL
-------------------------------------------
<td>
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="textbox_reg" Width="210px" />
<asp:RegularExpressionValidator ID="rfv_FileUpload1" runat="server" ErrorMessage="Invalid file name! select only image file types."
ValidationExpression=".*(\.[Jj][Pp][Gg]|\.[Gg][Ii][Ff]|\.[Pp][Nn][Gg]|\.[Jj][Pp][Ee][Gg]|\.[Bb][Mm][Pp])"
Display="None" ControlToValidate="FileUpload1">*</asp:RegularExpressionValidator>

<cc1:ValidatorCalloutExtender ID="vce_imagebefore1" TargetControlID="rfv_FileUpload1" runat="server">
</cc1:ValidatorCalloutExtender>
</td>


FILE UPLOAD THUMBNAIL

0 comments


FILE UPLOAD CONTROL

if(FU_Product.FileName != "")
{
Int32 intFileSize = Convert.ToInt32(FU_Product.PostedFile.ContentLength);
if(intFileSize <= 1000000)
{
String[] fileNameArray = FU_Product.FileName.Split('.');

string fileSavePath;
string origFileName;
string newFileName;

fileSavePath = "Images/";
origFileName = fileNameArray[0].ToString();
newFileName = Guid.NewGuid().ToString() + "." + fileNameArray[1];

FU_Product.SaveAs(Server.MapPath(fileSavePath + newFileName));

System.Drawing.Image Img = System.Drawing.Image.FromStream(FU_Product.PostedFile.InputStream);

Int32 thumbSize = 150;
Int32 width, height;

height = thumbSize;
width = Img.Width * thumbSize / Img.Height;

System.Drawing.Image thumbnailImage = Img.GetThumbnailImage(width, height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

thumbnailImage.Save(Server.MapPath(fileSavePath + "T" + newFileName));

parm[4] = new SqlParameter("@Image", SqlDbType.VarChar, 50);
parm[4].Value = newFileName.ToString();

}
else
{
lblError.Text = "File size should be < 1 MB.";
}

}


private bool ThumbnailCallback()
{
return true;
}






FUNCTION TO CLEAR THE CONTROLS

0 comments

-------------------------------------------------
FUNCTION TO CLEAR THE CONTROLS
public void ClearControls(Control parent )
{
foreach (Control c in parent.Controls)
{
if (c.Controls.Count > 0)
{
ClearControls(c);
}
else
{
switch (c.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox" :
((TextBox)c).Text = "";
break;
case "System.Web.UI.WebControls.DropDownList":
((DropDownList)c).SelectedIndex = -1;
break;
}
}
}
}

 

CodeAddict.com | Copyright 2009 Tüm Haklar? Sakl?d?r | Free Blogger Templates by GoogleBoy Download Free Wordpress Templates. Unblock through unblock myspace proxy, Hillsongs by Guitar Song Chords