Wednesday, November 17, 2010

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 offersettings : System.Web.UI.Page
{
SqlCommand cmd;
string getCon;
SqlConnection con;
SqlDataAdapter da;
DataTable dt;


protected void Page_Load(object sender, EventArgs e)
{
if(Session ["a"]==null)
{
Response.Redirect("adminlogin.aspx");
}
else
{
getCon = ConfigurationManager.AppSettings["SqlCon"];
con = new SqlConnection(getCon);
if (IsPostBack != true)
{
FillGrid();
}
}
}
public void FillGrid()
{
con.Open();

cmd = new SqlCommand("select * from offersettings ", con);
cmd.CommandType = CommandType.Text;
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
grdContact.DataSource = dt;
grdContact.DataBind();
con.Close();


}

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 txtconfig=(TextBox)grdContact.Rows[e.RowIndex].FindControl("txtconfig");
TextBox txtamount=(TextBox)grdContact.Rows[e.RowIndex].FindControl("txtamount");
CheckBox chkActive = (CheckBox)grdContact.Rows[e.RowIndex].FindControl("chkActive");

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//offer//") + d);
//MessageBox.Show(" " + d + " Successfully Uploaded");
}
else
{
file.SaveAs(Server.MapPath(".//images//offer//") + d);
//MessageBox.Show(" " + d + " Successfully Uploaded");
}
con.Open();
cmd = new SqlCommand("update offersettings set image='" + d.ToString() + "',config='" + txtconfig.Text + "',amount='" + txtamount.Text + "' where id='" + lblId.Text + "'", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
//contact.Update(txtName.Text, ddlSex.SelectedValue, cmbType.SelectedValue, flag,Convert.ToInt32(lblId.Text));

con.Close();
grdContact.EditIndex = -1;
FillGrid();


}
else
{
con.Open();

cmd = new SqlCommand("update offersettings set image='" + catcher.Text + "',config='" + txtconfig.Text + "',amount='" + txtamount.Text + "' where id='" + lblId.Text + "'", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
//contact.Update(txtName.Text, ddlSex.SelectedValue, cmbType.SelectedValue, flag,Convert.ToInt32(lblId.Text));

con.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 txtNewconfig = (TextBox)grdContact.FooterRow.FindControl("txtNewconfig");
TextBox txtnewamount = (TextBox)grdContact.FooterRow.FindControl("txtnewamount");

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//offer//") + d);
//MessageBox.Show(" " + d + " Successfully Uploaded");
}
else
{
file.SaveAs(Server.MapPath(".//images//offer//") + d);
//MessageBox.Show(" " + d + " Successfully Uploaded");
}
}
catch (Exception ex)
{
//this.ShowMessage(" " + ex.Message, i);
}



}
con.Open();
cmd = new SqlCommand("insert into offersettings values('" + d.ToString() + "','"+txtNewconfig.Text+"','"+txtnewamount.Text+"')", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.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)
{
Label lblId = (Label)grdContact.Rows[e.RowIndex].FindControl("lblId");
cmd = new SqlCommand("delete from offersettings where id = '" +lblId.Text+"'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
FillGrid();
}



}








How to use repeater inside of the grid in c#




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

public partial class Default2 : System.Web.UI.Page
{


protected void Page_Load(object sender, EventArgs e)
{
binddata();
}

// Function to bind data in data controls..
public void binddata()
{
// your connection string here
string str = "Data Source=.;Initial Catalog=master;Integrated Security=True";
SqlConnection con = new SqlConnection(str);
DataSet ds = new DataSet();
// name of your stored procedure,
SqlDataAdapter da = new SqlDataAdapter("getCompNews", con);
da.Fill(ds);

ds.Relations.Add("InnerVal",
ds.Tables[0].Columns["compname"],
// making a relation between two tables.
ds.Tables[1].Columns["compname"]);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkMore = (LinkButton)e.Row.FindControl("link");
Label lbl = (Label)e.Row.FindControl("Label1");
lnkMore.PostBackUrl = "~/Company.aspx?cmp=" + lbl.Text;
}
}
}

Using checkbox in the gridview 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.Text;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=True");
if (!IsPostBack)
{
pg_load();
}
}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
StringBuilder str = new StringBuilder();


int i = 0;


//for (int i = 0; i < GridView1.Rows.Count; i++)
//{
// GridViewRow row = GridView1.Rows[i];
// bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;

// if (isChecked)
// {


foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox chk = (CheckBox)gvr.FindControl("chkSelect");
if (chk.Checked==true)
{

str.Append(" "+GridView1.Rows[i].Cells[2].Text);
i++;
}
}


// prints out the result

Response.Write(str.ToString());
}
void pg_load()
{
cmd = new SqlCommand("select * from gridcheck", cn);
cmd.CommandType = CommandType.Text;
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}



How to use Repeater in c#



protected void lbtncreate_Click(object sender, EventArgs e)
{

multiview.ActiveViewIndex = 1;
cmd=new SqlCommand("select title from " + Session["a"] + "", con);
da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ArrayList al = new ArrayList();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
al.Insert(i, ds.Tables[0].Rows[i][0].ToString());
}
repeater.DataSource = al;
repeater.DataBind();
}

How to get the word count and highlighting the word

private void word_count_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(Form1.currpath + "sampl.txt");
//richTextBox1.Text = sr.ReadLine();
string contents = sr.ReadToEnd();
StreamWriter sw = new StreamWriter("richTextBox1");
sw.Write(contents);
sw.Close();
richTextBox1.Text = contents;
sr.Close();
label2.Text=Form1.query.ToString();
//string[] str = richTextBox1.Text.Split('');
string text = contents.ToString();

string word = label2.Text.ToString();
r = new Regex(@"\b" + word + @"\b", RegexOptions.IgnoreCase);
MatchCollection mc = r.Matches(contents);
a = mc.Count;
//int a = str.Length;
textBox1.Text = a.ToString();
//int b = label2.Text.Length;
//int d = richTextBox1.Find(label2.Text.ToString());
////int a = richTextBox1.Find(""); <br /> ////int b = richTextBox1.Find("");
////int c = d + b;
//richTextBox1.Select(d, b);
//richTextBox1.SelectionColor = Color.Goldenrod;
//richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);



string zoek = label2.Text;

int index = richTextBox1.Text.IndexOf(zoek);
while(index != -1)
{
richTextBox1.Select(index, zoek.Length);
richTextBox1.SelectionColor = Color.Red;
index = richTextBox1.Text.IndexOf(zoek, index + zoek.Length);
}



}

usage of repeater in c#





code:


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;

public partial class _Default : System.Web.UI.Page
{
SqlConnection con;

protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=.;Initial Catalog=Proj_saha;Integrated Security=True ");
SqlCommand cmd = new SqlCommand("SELECT * FROM history", con);
con.Open();

//place table information into DataSet
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
rptList.DataSource = ds;
rptList.DataBind();
con.Close();
}
}



design:-





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();

}

}