Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an extra column onto a gridview and data

I have a grid view which is populated after searching through a database, after this I have some calculations going on within a foreach loop like this

foreach(DataRow datarow in ds.Tables[0].Rows){
    resturantPostCodeData = checkpostcode(datarow["PostCode"].ToString().Trim());
    foreach(DataRow dr in resturantPostCodeData.Tables["geo"].Rows){
        rLatitude = Convert.ToDouble(dr["lat"].ToString().Trim());
        rLongitude = Convert.ToDouble(dr["lng"].ToString().Trim());
    }
    distanceResult = distance(myLatitude, myLongitude, rLatitude, rLongitude);
}

The value at the bottom of the foreach loop distanceResult I want those results to be added onto the end of the gridview in its own column

Any ideas of how to do this?

I'm making a web application in c# and asp.net

Hope you understand my question

like image 248
minglee Avatar asked Oct 22 '25 06:10

minglee


2 Answers

You can add the column to the DataTable before binding the GridView:

DataTable dt = ds.Tables[0];
dt.Columns.Add(new DataColumn("DistanceResult", System.Type.GetType("System.Double")));

foreach (DataRow row in dt.Rows)
{
    ...
    row["DistanceResult"] = distance(...);
}

gvDistance.DataSource = dt.DefaultView;
gvDistance.DataBind();

And you add the BoundField to the GridView:

<asp:GridView ID="gvDistance" runat="server" ...>
    <Columns>
        ...
        <asp:BoundField DataField="DistanceResult" ... />
    </Columns>
</asp:GridView>
like image 134
ConnorsFan Avatar answered Oct 23 '25 20:10

ConnorsFan


I ended up using these two lines of code similar to the answer given by ConnorsFan

ds.Tables[0].Columns.Add("Distance in miles", typeof(double));

later on in the code when assigning a value I used

datarow["Distance in miles"] = distanceResult;

Thanks for your help anyway people

like image 35
minglee Avatar answered Oct 23 '25 18:10

minglee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!