Prakash

Display Confirmation Message on Gridview Deleting

Write Javascript into head tag………

<head runat=”server”>
    <title>GridView Data Manipulation</title>
    <script type=”text/javascript” language=”javascript”>
        function ConfirmOnDelete(item)
        {
          if (confirm(“Are you sure to delete: ” + item + “?”)==true)
            return true;
          else
            return false;
        }
    </script>
</head>

Aspx page: Gridview

<Columns>
    <asp:BoundField DataField=”CustomerID” HeaderText=”ID” ReadOnly=”true” />
    <asp:BoundField DataField=”CompanyName” HeaderText=”Company”/>
    <asp:BoundField DataField=”ContactName” HeaderText=”Name”/>
    <asp:BoundField DataField=”ContactTitle” HeaderText=”Title” />
    <asp:BoundField DataField=”Address” HeaderText=”Address”/>
    <asp:BoundField DataField=”Country” HeaderText=”Country”/>
    <asp:CommandField ShowDeleteButton=”True” ShowEditButton=”True” />
</Columns>

.CS Page

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowState != DataControlRowState.Edit) // check for RowState
   {
     if (e.Row.RowType == DataControlRowType.DataRow) //check for RowType
     {
       string id = e.Row.Cells[0].Text; // Get the id to be deleted
       LinkButton lb = (LinkButton)e.Row.Cells[6].Controls[2]; //cast the ShowDeleteButton link to linkbutton
       if (lb != null)
       {
          lb.Attributes.Add(“onclick”, “return ConfirmOnDelete(‘” + id + “‘);”); //attach the JavaScript function with the ID as the paramter
       }      
      }
  }
}

Popup in gridview

Create a button in Gridiview set command name and command argument.

protected void grvViewInquiry_RowCommand(

object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == “Detail”)
{
int AppealId = Convert.ToInt32(e.CommandArgument.ToString());
string script = “window.open(‘ViewInquiryDetails.aspx?InqID=” + AppealId + “‘, ”,’width=800, height=500,top=130,left=90,resizable=yes’);”;
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), “Print”, script, true);
}
else if (e.CommandName == “Drawing”)
{
Response.Redirect(“ViewDrawings.aspx?InqID=” + Convert.ToString(e.CommandArgument));
}
}

Generate Storeprocedure Dynamically

sql
SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{

}
}
protected void btnConnect_Click(object sender, EventArgs e)
{
if (txtUserID.Text == “” && txtPassword.Text == “”)
{
conn = new SqlConnection();
string strConn = “Data Source=” + txtSQLName.Text + “; Initial Catalog=” + txtDBName.Text + “; Integrated Security=True”;
conn.ConnectionString = strConn;
conn.Open();
BindTable();
BindProcedure();
}
else
{
conn = new SqlConnection();
string strConn = “Data Source=” + txtSQLName.Text + “; Initial Catalog=” + txtDBName.Text + “; user id=” + txtUserID.Text + “;password=” + txtPassword.Text + “; Integrated Security=True”;
conn.ConnectionString = strConn;
conn.Open();
BindTable();
BindProcedure();
}
}
public void BindTable()
{
string str = “select Table_name from information_schema.tables”;
SqlDataAdapter adp = new SqlDataAdapter(str, conn);
DataSet ds = new DataSet();
adp.Fill(ds);
ddlTable.DataSource = ds;
ddlTable.DataTextField = “table_name”;
ddlTable.DataValueField = “table_name”;
ddlTable.DataBind();
}

public void BindProcedure()
{
string str = “select name from sys.procedures where object_definition(object_id) not like ‘%sp%'”;
SqlDataAdapter adp = new SqlDataAdapter(str, conn);
DataSet ds = new DataSet();
adp.Fill(ds);
ddlProcedure.DataSource = ds;
ddlProcedure.DataTextField = “name”;
ddlProcedure.DataValueField = “name”;
ddlProcedure.DataBind();
}

It will genrate insert store procedure, write below script on Generate button OnClick event
protected void btnGenerate_Click(object sender, EventArgs e)
{
conn = new SqlConnection();
string strConn = “Data Source=” + txtSQLName.Text + “; Initial Catalog=” + txtDBName.Text + “; user id=” + txtUserID.Text + “;password=” + txtPassword.Text + “; Integrated Security=True”;
conn.ConnectionString = strConn;
conn.Open();

string strTbl = “select column_name, data_type, character_maximum_length from information_schema.columns where columnproperty(object_id(table_name),column_name, ‘IsIdentity’)=0 and table_name='” + ddlTable.SelectedValue.ToString() + “‘”;

SqlDataAdapter adp = new SqlDataAdapter(strTbl, conn);
SqlCommand cmd1 = new SqlCommand(strTbl, conn);
SqlDataReader rdr;

rdr = cmd1.ExecuteReader();
DataTable schemaTable = rdr.GetSchemaTable();

string strPro;
ArrayList pra = new ArrayList();
ArrayList pram = new ArrayList();
string pp;

while (rdr.Read())
{
if (rdr[1].ToString() == “int”)
{
pp = “@” + rdr[0].ToString() + ” ” + “int”;
pra.Add(pp);
pram.Add(“@” + rdr[0].ToString());
}
else
{
pp = “@” + rdr[0].ToString() + ” ” + rdr[1].ToString() + “(” + rdr[2].ToString() + “)”;
pra.Add(pp);
pram.Add(“@” + rdr[0].ToString());
}
}

rdr.Close();

string ch = ddlGenerate.SelectedValue.ToString();
if (ch == “Insert Procedure”)
{
strPro = (“Create procedure ins” + ddlTable.SelectedValue.ToString() + ” (“);
for (int j = 0; j < pra.Count; j++)
{
strPro += (pra[j]);
if (j == pra.Count – 1)
{
}
else
{
strPro+=”,”;
}
}
strPro+=”) As “;
strPro +=”Insert into ” + ddlTable.SelectedValue.ToString() + ” values (“;
for (int j = 0; j < pra.Count; j++)
{
strPro += (pram[j]);
if (j == pram.Count – 1)
{
}
else
{
strPro += “,”;
}
}
strPro +=”)”;

Response.Write(strPro);
SqlCommand cmd = new SqlCo

Check IsIdentity true or false

Find SQL Table Cloumn name, data type,  column size

select column_name, data_type, character_maximum_length char from information_schema.columns where table_name=’tblCountry’

Find IsIdentity true columns

SELECT * from information_schema.columns where columnproperty(object_id(table_name),column_name, ‘IsIdentity’)=1
and table_name=’personal’

Find IsIdentity False Columns

SELECT * from information_schema.columns where columnproperty(object_id(table_name),column_name, ‘IsIdentity’)=0
and table_name=’personal’

Find Database, Tables, Procedure Names in SQL Server

Find all database names in sql server

select name from sys.databases

Find all tables names in sql server for perticular database

select Table_name from information_schema.tables

Find all procedure names in sql server for perticular database

select name from sys.procedures where object_definition(object_id) not like ‘%sp%’

SELECT name FROM sys.objects WHERE type = ‘P’

Send Email

You must have to use Gmail ID as From Email ID.

USE: using System.Net.Mail; // Namespace

OnSendMail Button Click Event :

try
{
SmtpClient obj = new SmtpClient(“smtp.gmail.com”);
obj.Credentials = new System.Net.NetworkCredential(“your@gmail.com”, “password”);
obj.Port = 587;
obj.Host = “smtp.gmail.com”;
obj.EnableSsl = true;

MailMessage message = new MailMessage(“your@gmail.com”,”to@yahoo.com”);
message.Subject = txtSUB.Text; // subject textbox’s text
message.Body = txtMSG.Text; // Message textbox’s text
obj.Send(message);
Response.Write(“Mail Successfully send”);
}
catch (SmtpException ex)
{
Response.Write(ex.Message.ToString());
}

File Extension Javascript Validation

<script language=”javascript” type=”text/javascript”>
function chkFile()
{
var fextension = document.getElementById(“<%=FileUpload1.ClientID %>”).value;

var exten = fextension.split(“.”);
var len=exten.length;
//alert(exten.length);

if(exten[len-1]==”doc” || exten[len-1]==”docx”)
{
alert(“File upload successfully”);
return true;
}
else
{
alert(“Please select doc file”);
return false;
}
}
</script>

Create Folder/Directory Check Existing

Create Folder/Directory and Check Existing or not

Here Session[“user”] is a name which will be created…. ‘upload’ is a floder/Director that already created.

if(Directory.Exists(Server.MapPath(“upload”) + “/” + Session[“user”].ToString()))
{
}
else
{
System.IO.Directory.CreateDirectory(Server.MapPath(“upload”) + “/” + Session[“user”].ToString());
}

DataTable : (Use For Make Shopping Cart)

First Time Page Load Gridview Shown as below

first_time_gridview

.aspx Page Coding

<div>
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” ShowFooter=”True” >
<Columns>
<asp:TemplateField HeaderText=”Rollno”>
<ItemTemplate>
<asp:Label ID=”lblRno” runat=”Server” Text=””></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Name”>
<ItemTemplate>
<asp:Label ID=”lblName” runat=”server” Text='<%# Eval(“name”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtName” runat=”server” Text=””></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”City”>
<ItemTemplate>
<asp:Label ID=”lblCity” runat=”server” Text='<%# Eval(“city”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtCity” runat=”server” Text=””></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Button ID=”btnAdd” runat=”server” Text=”ADD” OnClick=”btnAdd_Click” />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No Records
</EmptyDataTemplate>
</asp:GridView>
<asp:Button ID=”Button1″ runat=”server” OnClick=”Button1_Click” Style=”z-index: 100;
left: 16px; position: absolute; top: 192px” Text=”Insert Total Records from Grdiview” />
</div>

.aspx.cs Coding

DataTable dt = new DataTable();
DataColumn dc;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session[“cart”] = null;
MakeCart();
BindGrid();
}
}

//Define columns of DataTable
public void MakeCart()
{
dc = new DataColumn();
dc.ColumnName = “rollno”;
dc.DataType = typeof(int);
dt.Columns.Add(dc);

dc = new DataColumn();
dc.ColumnName = “name”;
dc.DataType = typeof(string);
dt.Columns.Add(dc);

dc = new DataColumn();
dc.ColumnName = “city”;
dc.DataType = typeof(string);
dt.Columns.Add(dc);

}

//Bind Records into Gridview
public void BindGrid()
{
if (dt.Rows.Count == 0)
{
DataRow dr = dt.NewRow();

dr[“name”] = “No Record”;
dr[“city”] = “No Record”;
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (Session[“cart”] == null)
{
MakeCart();
DataRow dr = dt.NewRow();
dr[“name”] = ((TextBox)GridView1.FooterRow.FindControl(“txtName”)).Text;
dr[“city”] = ((TextBox)GridView1.FooterRow.FindControl(“txtCity”)).Text;
dt.Rows.Add(dr);
Session[“cart”] = dt;
BindGrid();
}
else
{
dt = (DataTable)Session[“cart”];
DataRow dr = dt.NewRow();
dr[“name”] = ((TextBox)GridView1.FooterRow.FindControl(“txtName”)).Text;
dr[“city”] = ((TextBox)GridView1.FooterRow.FindControl(“txtCity”)).Text;
dt.Rows.Add(dr);
Session[“cart”] = dt;
BindGrid();
}
}

//Insert All Record from Gridview to DataSource  Sqlserver table.
protected void Button1_Click(object sender, EventArgs e)
{
dt = (DataTable)Session[“cart”];
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[“TESTConnectionString”].ToString());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = “insTy”;
for (int i=0; i <dt.Rows.Count; i++)
{
cmd.Parameters.AddWithValue(“@nm”, dt.Rows[i][“name”]);
cmd.Parameters.AddWithValue(“@ct”, dt.Rows[i][“city”]);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}