Saturday, December 1, 2007

Selecting or filtering value from DataSet

Suppose we have a District table having fields
District_Key
District_Name
District_StateKey
.....
.....

and have all the values in a dataset

DataSet dsState;

now we want to filter those value whoes state id is 4;
then we we can easily filter those value

DataRow[] dr = dsState.Tables[0].Select("State_Key=4");

Monday, November 26, 2007

Merging cells of a GridView

Suppose that we have a GridView data like this


Main ItemsubItemprice
item1s1123
item1s2456

item 2
s1878
item2s2456
item 2s31231
And we want to create like this



Main Itemsub Itemprice
item1s1123
s2456
item 2s1878
s2456
s31231

Then we can get it by using the following code

protected void GridView1_DataBound(object sender, EventArgs e)
{
string text = "";
int count = 0;
Hashtable ht = new Hashtable();

// loop through all rows to get row counts
foreach (GridViewRow gvr in GridView1.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow)
{
if (gvr.Cells[0].Text == text)
{
count++;
}
else
{
if (count > 0)
{
ht.Add(text, count);
}
text = gvr.Cells[0].Text;
count = 1;
}
}
}

if (count > 1)
{
ht.Add(text, count);
}


// loop through all rows again to set rowspan
text = "";
foreach (GridViewRow gvr in GridView1.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow)
{
if (gvr.Cells[0].Text == text)
{
gvr.Cells.Remove(gvr.Cells[0]);
}
else
{
text = gvr.Cells[0].Text;
gvr.Cells[0].RowSpan = Convert.ToInt32(ht[text]);
}
}
}
}

Tuesday, November 20, 2007

To get the number of pixel taken by a string using Graphics in C#

Bitmap myImage;
Graphics g;
myImage = new Bitmap(760, 800, PixelFormat.Format32bppRgb);
g = Graphics.FromImage(myImage);


SizeF size = g.MeasureString("shekhar", new Font("Arial", 8));
int lenght = (int)size.Width;
int height1 = (int)size.Height;

this will give the length and height in pixel of the string "shekhar"

Saturday, November 17, 2007

Parent Child Relation between two dropdown in a gridview

To change the drop down value form the other dropdown selected index change.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = (GridViewRow)((sender) as Control).NamingContainer;
DropDownList dr = (DropDownList)sender;
//DropDownList dr = (DropDownList)GridView1.FindControl("DropDownList1");

DropDownList dropdown2 =(DropDownList)row.FindControl("DropDownList2");
string condition = dr.SelectedValue.ToString();
SelectSubCategory(condition,dropdown2);//a function for filling the child gridview
}

GridView Changing the row style

If you want to change the style of row or column of a gridview then it can be done in the following way

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType ==DataControlRowType.DataRow)
{
for (int i = 2; i < e.Row.Cells.Count; i++)
{
e.Row.Cells[i].Style.Add("text-align", "right");
//e.Row.Cells[e.Row.Cells.Count-1].Text = "" + e.Row.Cells[i].Text + "";
}
}
}