Wednesday, April 1, 2009

Dynamic tree view creation using c#















using System;
using System.Configuration;
using System.Data;
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.IO;
using System.Data.SqlClient;


public partial class Default2 : System.Web.UI.Page
{
SqlCommand cmd;
SqlConnection cn;
//SqlDataReader dr;

protected void Page_Load(object sender, EventArgs e)
{

fill_Tree2();

}


void fill_Tree2()
{



DataSet PrSet = PDataset("Select productcode from ccc group by productcode");

TreeView1.Nodes.Clear();

foreach (DataRow dr in PrSet.Tables[0].Rows)
{

TreeNode tnParent = new TreeNode();

tnParent.Text = dr["productcode"].ToString();

//tnParent.Value = dr["ParentID"].ToString();
//tnParent.PopulateOnDemand = true;

TreeView1.Nodes.Add(tnParent);

FillChild(tnParent, tnParent.Value);
//FillChild1(tnParent, tnParent.Value);


tnParent.ToolTip = "Click to get Child";

//tnParent.SelectAction = TreeNodeSelectAction.SelectExpand;



tnParent.CollapseAll();
//tnParent.Selected = true;

}




}

public void FillChild(TreeNode parent, string ParentId)
{

DataSet ds = PDataset("Select * from ccc where productcode =" + ParentId+" order by productcode");

parent.ChildNodes.Clear();

foreach (DataRow dr in ds.Tables[0].Rows)
{

TreeNode child = new TreeNode();

child.Text = dr["productname"].ToString().Trim();
child.NavigateUrl = dr["url"].ToString().Trim();

//child.Value = dr["ChildId"].ToString().Trim();

if (child.ChildNodes.Count == 0)
{

child.PopulateOnDemand = true;

}

child.ToolTip = "Click to get Child";

child.SelectAction = TreeNodeSelectAction.SelectExpand;

child.CollapseAll();

parent.ChildNodes.Add(child);


}

}


//public void FillChild1(TreeNode parent, string ParentId)
//{

// DataSet ds = PDataset("Select * from ccc where productcode =" + ParentId);

// parent.ChildNodes.Clear();

// foreach (DataRow dr in ds.Tables[0].Rows)
// {

// TreeNode child1 = new TreeNode();

// child1.NavigateUrl = dr["url"].ToString().Trim();

// //child.Value = dr["ChildId"].ToString().Trim();

// if (child1.ChildNodes.Count == 0)
// {

// child1.PopulateOnDemand = true;

// }

// child1.ToolTip = "Click to get Child";

// child1.SelectAction = TreeNodeSelectAction.SelectExpand;

// child1.CollapseAll();

// parent.ChildNodes.Add(child1);

// }

//}




protected DataSet PDataset(string Select_Statement)
{

SqlConnection SqlCon = new SqlConnection("Data Source=.;Initial Catalog=govind;Integrated Security=True");

SqlDataAdapter ad = new SqlDataAdapter(Select_Statement, SqlCon);

DataSet ds = new DataSet();

ad.Fill(ds);

return ds;



}
protected void Button1_Click(object sender, EventArgs e)
{
cn = new SqlConnection("Data Source=.;Initial Catalog=govind;Integrated Security=True");
cmd= new SqlCommand("insert into ccc values('"+DropDownList1.SelectedItem.Text+"','"+TextBox1.Text+"','"+TextBox2.Text+"')",cn);
cmd.CommandType=CommandType.Text;
cn.Open();

cmd.ExecuteNonQuery();
fill_Tree2();
}
}





Upload image in grid with byte conversion








using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Data.SqlClient;
using System.IO;



public partial class _Default : System.Web.UI.Page
{
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgrid();
}

}

protected void Button1_Click1(object sender, EventArgs e)
{
Stream imgStream = fuImage.PostedFile.InputStream;

int imgLen = fuImage.PostedFile.ContentLength;

string imgName = txtImageName.Text;

byte[] imgBinaryData = new byte[imgLen];

int n = imgStream.Read(imgBinaryData, 0, imgLen);



//use the web.config to store the connection string

SqlConnection connection = new SqlConnection("Data Source=.; Initial Catalog =master; Uid=sa; Pwd=;");
SqlCommand command = new SqlCommand("INSERT INTO imagetogrid (imagename,image) VALUES ( @img_name, @img_data)", connection);



SqlParameter param0 = new SqlParameter("@img_name", SqlDbType.VarChar, 50);

param0.Value = imgName;

command.Parameters.Add(param0);



SqlParameter param1 = new SqlParameter("@img_data", SqlDbType.Image);

param1.Value = imgBinaryData;

command.Parameters.Add(param1);



connection.Open();

int numRowsAffected = command.ExecuteNonQuery();

connection.Close();

fillgrid();



}
public void fillgrid()
{



SqlConnection connection = new SqlConnection("Data Source= .; Initial Catalog =master; Uid=sa; Pwd=;");
SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [imagetogrid]", connection);

SqlDataAdapter ada = new SqlDataAdapter(command);

ada.Fill(dt);

gvImages.DataSource = dt;

gvImages.DataBind();

}

}



Editable grid with images using c#













using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

using System.IO;

 

 

 

public partial class _Default : System.Web.UI.Page

{

SqlCommand cmd;

SqlConnection cn;

SqlDataAdapter da;

DataTable dt;

 

protected void Page_Load(object sender, EventArgs e)

{

cn = new SqlConnection("Data Source=HCL-AFB25EB7B70\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");

if (IsPostBack!=true)

{

FillGrid();

}

}

public void FillGrid()

{

cn.Open();

cmd = new SqlCommand("select * from michael ", cn);

cmd.CommandType = CommandType.Text;

da = new SqlDataAdapter(cmd);

dt = new DataTable();

da.Fill(dt);

grdContact.DataSource = dt;

grdContact.DataBind();

cn.Close();

}

protected void grdContact_RowDataBound(object sender, GridViewRowEventArgs e)

{

//ContactTypeTableAdapter contactType = new ContactTypeTableAdapter();

cmd = new SqlCommand("select type from michael group by type ", cn);

cmd.CommandType = CommandType.Text;

da = new SqlDataAdapter(cmd);

dt = new DataTable();

da.Fill(dt);

DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbType");

DropDownList ddlSex = (DropDownList)e.Row.FindControl("ddlSex");

if (cmbType != null)

{

cmbType.DataTextField = "type";

cmbType.DataSource = dt;

//cmbType.DataValueField = "Id";

cmbType.DataBind();

cmbType.SelectedValue = grdContact.DataKeys[e.Row.RowIndex].Values[1].ToString();

ddlSex.SelectedValue = grdContact.DataKeys[e.Row.RowIndex].Values[2].ToString();

//DataTable contactTypes = contactType.GetData();

//if (e.Row.RowType == DataControlRowType.DataRow)

//{

//Label lblType = (Label)e.Row.FindControl("lblType");

//if (lblType != null)

//{

// int typeId = Convert.ToInt32(lblType.Text);

// lblType.Text = (string)dt.GetType(typeId);

//}

//DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbType");

//if (cmbType != null)

//{

// cmbType.DataSource = dt;

// cmbType.DataTextField = "TypeName";

// cmbType.DataValueField = "Id";

// cmbType.DataBind();

// //cmbType.SelectedValue = grdContact.DataKeys[e.Row.RowIndex].Values[1].ToString();

//}

} cmd = new SqlCommand("select types from type", cn);

cmd.CommandType = CommandType.Text;

da = new SqlDataAdapter(cmd);

dt = new DataTable();

da.Fill(dt);

if (e.Row.RowType == DataControlRowType.Footer)

{

DropDownList cmbNewType = (DropDownList)e.Row.FindControl("cmbNewType");

cmbNewType.DataTextField = "types";

cmbNewType.DataSource = dt;

cmbNewType.DataBind();

}

}

protected void grdContact_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

grdContact.EditIndex = -1;

FillGrid();

}

protected void grdContact_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

Label catcher = (Label)grdContact.Rows[e.RowIndex].FindControl("catcher");

//Label lblId = (Label)grdContact.Rows[e.RowIndex].FindControl("lblId");

TextBox txtName = (TextBox)grdContact.Rows[e.RowIndex].FindControl("txtName");

CheckBox chkActive = (CheckBox)grdContact.Rows[e.RowIndex].FindControl("chkActive");

DropDownList cmbType = (DropDownList)grdContact.Rows[e.RowIndex].FindControl("cmbType");

DropDownList ddlSex = (DropDownList)grdContact.Rows[e.RowIndex].FindControl("ddlSex");

FileUpload image = (FileUpload)grdContact.Rows[e.RowIndex].FindControl("FileUpload1");

 

string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*~";

Random randNum = new Random();

char[] chars = new char[5];

int allowedCharCount = _allowedChars.Length;

for (int i = 0; i < 5; i++)

{

chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];

}

 

string s = new string(chars);

 

//HttpFileCollection uploadFilCol = Request.Files;

//for (int i = 0; i < uploadFilCol.Count; i++)

//{

string ss = image.PostedFile.FileName;

HttpPostedFile file = image.PostedFile;

string fileExt = Path.GetExtension(file.FileName).ToLower();

string fileName = Path.GetFileName(file.FileName);

string c = fileName.ToString();

string[] b = c.Split('.');

string x = b[0].ToString();

string d = x.ToString() + s.ToString() + fileExt.ToString();

if (fileName != string.Empty)

{

//try

// {

if (fileExt == ".jpg" || fileExt == ".gif")

{

file.SaveAs(Server.MapPath("./images/") + d);

//MessageBox.Show(" " + d + " Successfully Uploaded");

}

else

{

file.SaveAs(Server.MapPath("./images/") + d);

//MessageBox.Show(" " + d + " Successfully Uploaded");

}

cn.Open();

cmd = new SqlCommand("update michael set name='" + txtName.Text + "',sex='" + ddlSex.SelectedValue + "',type='" + cmbType.SelectedValue + "',image='" + d.ToString() + "' where id='" + ((TextBox)this.grdContact.Rows[e.RowIndex].Cells[0].Controls[0]).Text + "'", cn);

cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

//contact.Update(txtName.Text, ddlSex.SelectedValue, cmbType.SelectedValue, flag,Convert.ToInt32(lblId.Text));

cn.Close();

grdContact.EditIndex = -1;

FillGrid();

}

else

{

cn.Open();

cmd = new SqlCommand("update michael set name='" + txtName.Text + "',sex='" + ddlSex.SelectedValue + "',type='" + cmbType.SelectedValue + "',image='" +catcher.Text + "' where id='" + ((TextBox)this.grdContact.Rows[e.RowIndex].Cells[0].Controls[0]).Text + "'", cn);

cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

//contact.Update(txtName.Text, ddlSex.SelectedValue, cmbType.SelectedValue, flag,Convert.ToInt32(lblId.Text));

cn.Close();

grdContact.EditIndex = -1;

FillGrid();

}

// catch (Exception ex)

//{

//this.ShowMessage(" " + ex.Message, i);

//}

}

//ContactTableAdapter contact = new ContactTableAdapter();

//bool flag = false;

protected void grdContact_RowCommand(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName.Equals("Insert"))

{

TextBox txtNewName = (TextBox)grdContact.FooterRow.FindControl("txtNewName");

//CheckBox chkNewActive = (CheckBox)grdContact.FooterRow.FindControl("chkNewActive");

DropDownList cmbNewType = (DropDownList)grdContact.FooterRow.FindControl("cmbNewType");

DropDownList ddlNewSex = (DropDownList)grdContact.FooterRow.FindControl("ddlNewSex");

FileUpload image1=(FileUpload)grdContact.FooterRow.FindControl("FileUpload2");

//if (chkNewActive.Checked) flag = true; else flag = false;

string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*~";

Random randNum = new Random();

char[] chars = new char[5];

int allowedCharCount = _allowedChars.Length;

for (int i = 0; i < 5; i++)

{

chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];

}

string s = new string(chars);

//HttpFileCollection uploadFilCol = Request.Files;

//for (int i = 0; i < uploadFilCol.Count; i++)

//{

string ss = image1.PostedFile.FileName;

HttpPostedFile file = image1.PostedFile;

string fileExt = Path.GetExtension(file.FileName).ToLower();

string fileName = Path.GetFileName(file.FileName);

string c = fileName.ToString();

string[] b = c.Split('.');

string x = b[0].ToString();

string d = x.ToString() + s.ToString() + fileExt.ToString();

if (fileName != string.Empty)

{

try

{

if (fileExt == ".jpg" || fileExt == ".gif")

{

file.SaveAs(Server.MapPath("./images/") + d);

//MessageBox.Show(" " + d + " Successfully Uploaded");

}

else

{

file.SaveAs(Server.MapPath("./images/") + d);

//MessageBox.Show(" " + d + " Successfully Uploaded");

}

}

catch (Exception ex)

{

//this.ShowMessage(" " + ex.Message, i);

}

}

cn.Open();

cmd = new SqlCommand("insert into michael values('" + txtNewName.Text + "','" + ddlNewSex.SelectedValue + "','" + cmbNewType.SelectedValue + "','" + d.ToString() + "')", cn);

cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

cn.Close();

//contact.Insert(txtNewName.Text, ddlNewSex.SelectedValue, cmbNewType.SelectedValue, flag);

FillGrid();

}

}

protected void grdContact_RowEditing(object sender, GridViewEditEventArgs e)

{

grdContact.EditIndex = e.NewEditIndex;

FillGrid();

}

protected void grdContact_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

//cmd = new SqlCommand("delete from empdetails where emp_id='" + this.gd_Items.Rows[e.RowIndex].Cells[0].Text + "'", cn);

//cn.Open();

//cmd.ExecuteNonQuery();

//gd_Items.EditIndex = -1;

//cn.Close();

cmd = new SqlCommand("delete from michael where id = '" + this.grdContact.Rows[e.RowIndex].Cells[0].Text + "'", cn);

cn.Open();

cmd.ExecuteNonQuery();

cn.Close();

FillGrid();

}

 

 

}

 








<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="offersettings.aspx.cs" Inherits="offersettings" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server" >

<asp:Panel ID="Panel1" runat="server" Height="3px" Width="69px">

<form id="form1" runat="server">

<div>

<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="Medium" Font-Underline="True" ForeColor="#C00000" Text="New Offer Settings" Width="204px">asp:Label>

<br />

<table align="center">

<tr>

<td>

<asp:GridView ID="grdContact" runat="server" DataKeyNames="Id" OnRowDeleting="grdContact_RowDeleting" AutoGenerateColumns="False" OnRowCancelingEdit="grdContact_RowCancelingEdit" OnRowEditing="grdContact_RowEditing" OnRowUpdating="grdContact_RowUpdating" OnRowCommand="grdContact_RowCommand" ShowFooter="True" CellPadding="3" BackColor="#DEBA84" BorderColor="#DEBA84" BorderWidth="1px" BorderStyle="None" CellSpacing="2" Height="213px" Width="246px" >

<Columns>

<asp:TemplateField HeaderText="ID">

<ItemTemplate>

<asp:Label ID="lblid" runat="server" Text='<%# Bind("id") %>'>asp:Label>

ItemTemplate>

asp:TemplateField>

<asp:TemplateField HeaderText="image">

<EditItemTemplate>

<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:Label ID="catcher" runat="server" Visible="false" Text='<%# Bind("image") %>'>asp:Label>

EditItemTemplate>

<ItemTemplate>

<asp:Image ID="Image1" Width="80px" Height="80px" ImageAlign="TextTop" ImageUrl='<%# "./images/offer/"+ Eval("image") %>' runat="server" />

<%-- --%> <%----%>

ItemTemplate>

<FooterTemplate>

<asp:FileUpload ID="FileUpload2" runat="server" Visible="true"/>

FooterTemplate>

<HeaderStyle HorizontalAlign="Left" />

asp:TemplateField>

<asp:TemplateField HeaderText="Configuration">

<EditItemTemplate>

<asp:TextBox ID="txtconfig" runat="server" TextMode="MultiLine" Text='<%# Bind("config") %>'>

asp:TextBox>

EditItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtNewconfig" runat="server" TextMode="MultiLine" Visible="true">asp:TextBox>

FooterTemplate>

<ItemTemplate>

<asp:Label ID="lblconfig" runat="server" Text='<%# Bind("config") %>'>asp:Label>

ItemTemplate>

<HeaderStyle HorizontalAlign="Left" />

asp:TemplateField>

<asp:TemplateField HeaderText="amount">

<EditItemTemplate>

<asp:TextBox ID="txtamount" runat="server" Text='<%# Bind("amount") %>'>asp:TextBox>

EditItemTemplate>

<ItemTemplate>

<asp:Label ID="lblamount" runat="server" Text='<%# Bind("amount") %>'>asp:Label>

ItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtnewamount" runat="server" >asp:TextBox>

FooterTemplate>

<HeaderStyle HorizontalAlign="Left" />

asp:TemplateField>

<asp:TemplateField HeaderText="Edit" ShowHeader="False">

<EditItemTemplate>

<asp:LinkButton ID="lbkUpdate" runat="server" CausesValidation="True" CommandName="Update" Text="Update">asp:LinkButton>

<asp:LinkButton ID="lnkCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel">asp:LinkButton>

EditItemTemplate>

<FooterTemplate>

<asp:LinkButton ID="lnkAdd" runat="server" CausesValidation="False" ForeColor="blue" CommandName="Insert" Text="Insert" Visible="true">asp:LinkButton>

FooterTemplate>

<ItemTemplate>

<asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit">asp:LinkButton>

ItemTemplate>

<HeaderStyle HorizontalAlign="Left" />

<ControlStyle ForeColor="Green" />

asp:TemplateField>

<asp:TemplateField HeaderText="Delete" ShowHeader="False">

<ItemTemplate>

<asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete">asp:LinkButton>

ItemTemplate>

<HeaderStyle HorizontalAlign="Left" />

<ControlStyle ForeColor="Red" />

asp:TemplateField>

Columns>

<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />

<SelectedRowStyle BackColor="#738A9C" ForeColor="White" Font-Bold="True" />

<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />

<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />

<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />

asp:GridView>

td>tr>

table>

div>

form>

asp:Panel>

asp:Content>