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]);
}
}
}
}