ASP.NET DataGrid, after I bind data to the GridView, how can I adjust the column header width so it's not wrapped.
here is the code behind
using (SqlConnection _conn = new SqlConnection(_sqlServer))
{
using (SqlCommand _cmd = _conn.CreateCommand())
{
_cmd.CommandText =
"select * from Clients order by ID desc";
using (SqlDataAdapter _da = new SqlDataAdapter(_cmd))
{
DataSet _ds = new DataSet();
_da.Fill(_ds);
gvClients.DataSource = _ds.Tables[0];
gvClients.DataBind();
}
}
}
.aspx
<asp:GridView ID="gvClients" runat="server">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID"/>
<asp:BoundField DataField="Client" HeaderText="Client" SortExpression="Client" />
<asp:BoundField DataField="ClientID" HeaderText="Client ID" SortExpression="ClientID" />
<asp:BoundField DataField="ContactInfo" HeaderText="Contact Info" SortExpression="ContactInfo" />
<asp:BoundField DataField="AssignedTech" HeaderText="Assigned Tech" SortExpression="AssignedTech" />
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
</Columns>
</asp:GridView>
I have tried
<asp:BoundField DataField="ContactInfo" HeaderText="Contact Info" ItemStyle-Width = "300px" SortExpression="ContactInfo" />
<asp:BoundField DataField="ContactInfo" HeaderText="Contact Info" HeaderStyle-Width="300px" SortExpression="ContactInfo" />
you can also try this
private void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
e.Row.Cells[3].Width = Unit.Pixel(300);
}
you can also try CSS solution for not wrapping header row of
th {
white-space: nowrap;
}
You are Adjust your header column in Row data bound Event of Grid View
Using following Code
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[ColumnIndex].Width = Unit.Pixel(Width in Number);
}
<asp:GridView runat="server" HeaderStyle-Wrap="false"></asp:GridView>
Related
I have two gridviews each with their own table.
I'm trying to make it so I can select a row(s) from GridViewA and move it to GridViewB (not copy). Then be able to move the selected row(s) from GridViewB back to GridViewA.
GridViewA (populated with SqlDataSource1)
<asp:GridView ID="grdA" runat="server" CellPadding="4" AllowPaging="True" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True" DataKeyNames="ID" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="Vertical" Width="75%">
<AlternatingRowStyle BackColor="white" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="Data1"HtmlEncode="false"/>
<asp:BoundField DataField="Data2" HtmlEncode="false"/>
<asp:BoundField DataField="Data3" HtmlEncode="false"/>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkBox" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
GridViewB (populated with SqlDataSource2)
<asp:GridView ID="grdB" runat="server" CellPadding="4" AllowPaging="True" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True" DataKeyNames="ID" DataSourceID="SqlDataSource2" ForeColor="#333333" GridLines="Vertical" Width="75%">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="Data1"HtmlEncode="false"/>
<asp:BoundField DataField="Data2" HtmlEncode="false"/>
<asp:BoundField DataField="Data3" HtmlEncode="false"/>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkBox2" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
Button to move row(s) from GridViewA to GridViewB. It works but I'm not sure how to delete the row from GridViewA after moving to GridViewB
protected void btnSubmit_Click(object sender, EventArgs e)
{
string DataA, DataB, DataC;
var connectionString = ConfigurationManager.ConnectionStrings["Database1"].ConnectionString;
var insertStatement = "INSERT INTO SqlTableB (Data1, Data2, Data3) VALUES (#Data1, Data2, Data3)";
using (var sqlConnection = new SqlConnection(connectionString))
foreach (GridViewRow gRow in grdA.Rows)
{
CheckBox cb = (gRow.FindControl("chkBox") as CheckBox);
if (cb.Checked)
{
DataA = Convert.ToString(gRow.Cells[1].Text);
DataB = Convert.ToString(gRow.Cells[2].Text);
DataC = Convert.ToString(gRow.Cells[3].Text);
using (var sqlCommand = new SqlCommand(insertStatement, sqlConnection))
{
sqlConnection.Open();
sqlCommand.Parameters.AddWithValue("#Data1", DataA);
sqlCommand.Parameters.AddWithValue("#Data2", DataB);
sqlCommand.Parameters.AddWithValue("#Data3", DataC);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
}
}
}
Please let me know if I can make the issue more clear, thank you
I would approach the problem this way:
First, make sure you set the PK row id for the Grid (that way you dont have to include in the display, or markup).
So USE "datakeys" setting of the grid - this will help a lot.
So, say two grids, like this:
<div style="float:left;width: 40%">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" cssclass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" SortExpression="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdMoveRight" runat="server" Text="Move->" style="float:right" CssClass="btn" OnClick="cmdMoveRight_Click" />
</div>
<div style="float:left;width: 40%;margin-left:10px">
<asp:GridView ID="GridView2" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" cssclass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" SortExpression="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdMoveMoveLeft" runat="server" Text="<-Move" CssClass="btn" OnClick="cmdMoveMoveLeft_Click" />
</div>
Code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrids();
}
}
void LoadGrids()
{
SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotelsA");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
cmdSQL.CommandText = "SELECT * from tblHotelsB";
GridView2.DataSource = MyRstP(cmdSQL);
GridView2.DataBind();
}
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
Ok, so now we have this:
Ok, now a button to move right, and one to move left. Code is:
protected void cmdMoveRight_Click(object sender, EventArgs e)
{
// move records right A to table B
string strSQL =
"INSERT INTO tblHotelsB (FirstName, LastName, HotelName, Description) " +
"SELECT FirstName, LastName, HotelName, Description FROM tblHotelsA " +
"WHERE tblHotelsA.id = #ID";
string strSQLDel = "DELETE FROM tblHotelsA WHERE ID = #ID";
MoveRows(GridView1,strSQL,strSQLDel);
}
protected void cmdMoveMoveLeft_Click(object sender, EventArgs e)
{
// move records right A to table B
string strSQL =
"INSERT INTO tblHotelsA (FirstName, LastName, HotelName, Description) " +
"SELECT FirstName, LastName, HotelName, Description FROM tblHotelsB " +
"WHERE tblHotelsB.id = #ID";
string strSQLDel = "DELETE FROM tblHotelsB WHERE ID = #ID";
MoveRows(GridView2, strSQL,strSQLDel);
}
void MoveRows(GridView gv,string strSQL, string strSQLDel)
{
foreach (GridViewRow OneRow in gv.Rows)
{
CheckBox ckBox = OneRow.FindControl("cHkSel") as CheckBox;
if (ckBox.Checked)
{
int PKID = (int)gv.DataKeys[OneRow.RowIndex]["ID"];
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
SqlRun(cmdSQL);
// delte the row
cmdSQL.CommandText = strSQLDel;
SqlRun(cmdSQL);
}
}
// now re-load both grids to reflect changes
LoadGrids();
}
public void SqlRun(SqlCommand cmdSQL)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
}
I just want to ask how can I have different links in my GridView.
Here is my HTML code for my GridView.
<asp:GridView ID="gridsummary" runat="server" AutoGenerateColumns="False"
HorizontalAlign="Left">
<Columns>
<asp:BoundField DataField="sstat" HeaderText="STATUS">
<ItemStyle Width="250px" HorizontalAlign="Left" VerticalAlign="Top" />
</asp:BoundField>
<asp:BoundField DataField="ctr" HeaderText="COUNT" >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Top" Width="150px" />
</asp:BoundField>
<asp:BoundField DataField="sstat" HtmlEncode="False" DataFormatString="<a href='webViewDelivered.aspx'>View</a>" />
</Columns>
<HeaderStyle CssClass="GRIDVIEW_TITLE" />
<RowStyle CssClass="GRIDVIEW_DETAILS" />
</asp:GridView>
Here is my c# code when loading the page.
if (!IsPostBack)
{
dsSummary = dm.MainDash(Session["Username"].ToString(), "");
gridsummary.DataSource = dsSummary.Tables[0];
gridsummary.DataBind();
string sDelivered = string.Empty;
string sNoAirway = string.Empty;
string sIntransit = string.Empty;
string sReturned = string.Empty;
DataTable dt = new DataTable();
dt = dsSummary.Tables[0];
List<string> slistPostal = new List<string>();
foreach (DataRow dr in dt.Rows)
{
if (dr[0].ToString() == "DELIVERED")
{
sDelivered = dr["HTML"].ToString();
Delivered.InnerHtml = sDelivered;
}
if (dr[0].ToString() == "FOR PROCESSING")
{
sNoAirway = dr["HTML"].ToString();
NoAirway.InnerHtml = sNoAirway;
}
if (dr[0].ToString() == "IN TRANSIT")
{
sIntransit = dr["HTML"].ToString();
Intransit.InnerHtml = sIntransit;
}
if (dr[0].ToString() == "RETURNED")
{
sReturned = dr["HTML"].ToString();
Returned.InnerHtml = sReturned;
}
}
}
What I want is something like this:
If I select the first row of my GridView the third BoundField will be this
<asp:BoundField DataField="sstat" HtmlEncode="False" DataFormatString="<a href='webViewDelivered.aspx'>View</a>" />
If I select the 2nd row the third BoundField will change to this
<asp:BoundField DataField="sstat" HtmlEncode="False" DataFormatString="<a href='webViewForProcessing.aspx'>View</a>" />
When a different row is selected href will be modified depending on the page that I want to load, is there a condition for that?
PS: My stored procedure is quite long so for your reference sstat is equal to the conditions in above.. for example in my SP i have select 'DELIVERED' AS sstat
Use TemplateField not BoundField
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<HyperLink ID="RedirectBtn" runat="server"
OnClick="RedirectBtn_Click" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
You can add whatever you want in OnRowDataBound event of the grid after that. If your RowDataBound event is called Grid_RowDataBound
protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem == null)
return;
DataRowView row = e.Row.DataItem as DataRowView;
HyperLinkbtn = e.Row.FindControl("RedirectBtn") as HyperLink;
b.NavigateUrl = "write your link";
//if you want to open new tab
b.Target="_blank";
}
You are adding the event to the grid like this:
OnRowDataBound="Grid_RowDataBound"
If you want you can make it with a tag, if your href is static and you don't need to make changes for every row.
<asp:TemplateField HeaderText="YourHeaderText">
<ItemTemplate>
<a target='_blank' href='Your link'>Text/a>
</ItemTemplate>
</asp:TemplateField>
I have to download pdf file using link button that is binded with grid view. I have uploaded pdf into database table as in varbinary format. The given below table cad_file column contains pdf files.
While clicking "version_no" drop down list, I have to bind pdf and all other datas with gridview. And by click on that I want to download pdf. How can I do that. Help me to find a proper solution. Thank you.
Code:
protected void ddlVersionNo_SelectedIndexChanged(object sender, EventArgs e)
{
ShadingAnalysisDataSetTableAdapters.tbl_CadFileUploadTableAdapter cd;
cd = new ShadingAnalysisDataSetTableAdapters.tbl_CadFileUploadTableAdapter();
DataTable dt = new DataTable();
dt = cd.GetGvCad2(ddlSiteID.SelectedValue, int.Parse(ddlVersionNo.SelectedValue));
gvCadPdf.DataSource = dt;
gvCadPdf.DataBind();
}
SQL:
SELECT Id, District, SiteName, Site_ID, Created_Date, Created_By, State, Updated_Date, Updated_By, Version_Status, Version_No, Cad_File, Cad_File_Name FROM tbl_CadFileUpload WHERE (Site_ID = #Site_ID) AND (Version_No = #Version_No)
ASPX:
DB:
ScreenShot1:
ScreenShot2:
try this code.
DropDown SelectedIndexChanged
protected void ddlVersionNo_SelectedIndexChanged(object sender, EventArgs e)
{
int Demo=ddlVersionNo.SelectedValue;
}
GridViewRowCommand
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "LinkButton")
{
ShadingAnalysisDataSetTableAdapters.tbl_CadFileUploadTableAdapter cd;
cd = new ShadingAnalysisDataSetTableAdapters.tbl_CadFileUploadTableAdapter();
DataTable dt = new DataTable();
dt = cd.GetGvCad2(ddlSiteID.SelectedValue, int.Parse(Demo));
gvCadPdf.DataSource = dt;
gvCadPdf.DataBind();
}
}
given below is the working code for download pdf using link button. Thank you all for valuable comments.
Code:
protected void lnkDownload_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
int fileid = Convert.ToInt32(gvCadPdf.DataKeys[gvrow.RowIndex].Value.ToString());
string name, type;
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = " SELECT Id, Cad_File, Cad_File_Name, type From tbl_CadFileUpload WHERE Id=#Id";
cmd.Parameters.AddWithValue("#id", fileid);
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Response.ContentType = dr["type"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + dr["Cad_File_Name"] + "\"");
Response.BinaryWrite((byte[])dr["Cad_File"]);
Response.End();
}
}
}
}
ASPX:
<asp:GridView ID="gvCadPdf" runat="server" OnSelectedIndexChanged="gvCadPdf_SelectedIndexChanged" AutoGenerateColumns="False" DataKeyNames="Id">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Sl No" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="State" HeaderText="State" ReadOnly="True" SortExpression="State" />
<asp:BoundField DataField="District" HeaderText="District" ReadOnly="True" SortExpression="District" />
<asp:BoundField DataField="SiteName" HeaderText="Site Name" ReadOnly="True" SortExpression="SiteName" />
<asp:BoundField DataField="Site_ID" HeaderText="Site ID" ReadOnly="True" SortExpression="Site_ID" />
<asp:BoundField DataField="Created_Date" HeaderText="Created Date" ReadOnly="True" SortExpression="Created_Date" />
<asp:BoundField DataField="Updated_Date" HeaderText="Updated Date" ReadOnly="True" SortExpression="Updated_Date" />
<asp:BoundField DataField="Created_By" HeaderText="Created By" ReadOnly="True" SortExpression="Created_By" />
<asp:BoundField DataField="Updated_By" HeaderText="Updated By" ReadOnly="True" SortExpression="Updated_By" />
<asp:BoundField DataField="Version_No" HeaderText="Version No" ReadOnly="True" SortExpression="Version_No" />
<asp:BoundField DataField="Cad_File_Name" HeaderText="Cad File Name" ReadOnly="True" SortExpression="Cad_File_Name" />
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
DB:
I am trying to learn how to add an additional nested table inside the firstLevelGrid but I am not succeding. Any help would be appreciated.
Particularly I am doing something wrong in managing the OnRowDataBound when I create the second level grid, both in the markup and the code behind.
This is the code I have that generate the grid and the first level. I have not added my attempts for the second level grid just to avoid to mess up the code.
It is not homework, I am not a professional coder and I am a selflearner.
<div>
<asp:GridView ID="zeroLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="Grid"
DataKeyNames="Code" OnRowDataBound="OnRowDataBoundZeroLevel">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="firstLevelPanel" runat="server" Style="display: none">
<asp:GridView ID="firstLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<Columns>
<!-- Here is where I add the second level grid copying the entire block "TemplateFiled" of the firstLevelGrid and renaming it secondLevel...-->
<asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="Code" HeaderText="Code" />
<asp:BoundField ItemStyle-Width="150px" DataField="Description" HeaderText="Description" />
<asp:BoundField ItemStyle-Width="150px" DataField="Quantity" HeaderText="Quantity" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="Code" HeaderText="Code" />
<asp:BoundField ItemStyle-Width="150px" DataField="Description" HeaderText="Description" />
<asp:BoundField ItemStyle-Width="150px" DataField="Quantity" HeaderText="Quantity" />
</Columns>
</asp:GridView>
and my c# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
zeroLevelGrid.DataSource = GetData("select top 10 * from Table_xx");//top10 only for test purposes
zeroLevelGrid.DataBind();
}
}
private static DataTable GetData(string query)
{
string strConnString = ConfigurationManager.ConnectionStrings["Test1ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = query;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void OnRowDataBoundZeroLevel(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string code = zeroLevelGrid.DataKeys[e.Row.RowIndex].Value.ToString();
GridView firstLevelGrid = e.Row.FindControl("firstLevelGrid") as GridView;
firstLevelGrid.DataSource = GetData(string.Format("IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'{0}')) SELECT * from [{0}]", code));
firstLevelGrid.DataBind();
}
}
//here is where I add an OnRowDataBound event copying the above one as OnRowDataBoundFirstLevel
//but then I get lost...
}
I would be glad if someone could indicate me how to add an additional level of nested grid inside the firstLevelGrid identical to it. I would be happy to offer a bounty to get this right but unfortunatelly I do not have enough rep yet. Thank you a lot.
Similart to your firstLevelGrid, you have to declare the third level grid inside the firstLevelGrid as a template column
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="secondLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<Columns>
<%--Your columns go here--%>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
Then handle OnRowDataBound event for the firstLevelGrid
OnRowDataBound="firstLevelGrid_OnRowDataBound"
In the RowDataBound event you can get the grid view, data key and bind the child grid
protected void firstLevelGrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView firstLevelGrid = e.Row.NamingContainer as GridView;
string code = firstLevelGrid.DataKeys[e.Row.RowIndex].Value.ToString();
GridView secondLevelGridView = e.Row.FindControl("secondLevelGrid") as GridView;
secondLevelGridView.DataSource = //GetData
secondLevelGridView.DataBind();
}
}
I don't need to use a Gridview if it's not the proper way to do this, some have told me to use a Repeater but I don't know how. Assistance needed!
Looks like this right now:
I want to separate it out by location (a column in the sql table):
ASPX
<asp:GridView runat="server" ID="ReportGrid" CssClass="table" AutoGenerateColumns="False"
AllowPaging="True" BorderColor="#E8CC6B" BorderStyle="Solid" BorderWidth="1px"
Width="100%" OnRowDataBound="ReportGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Owes" HeaderText="Owes" />
<asp:BoundField DataField="Paid" HeaderText="Paid" />
<asp:BoundField DataField="OrigAmt" HeaderText="Amt" />
<asp:BoundField DataField="SubmitDate" DataFormatString="{0:MM/dd/yy}" HeaderText="Date" />
</Columns>
</asp:GridView>
ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindGridView();
}
public void bindGridView()
{
string connStr = "";
SqlConnection mySQLconnection = new SqlConnection(connStr);
if (mySQLconnection.State == ConnectionState.Closed)
{
mySQLconnection.Open();
}
SqlCommand mySqlCommand = new SqlCommand(#"SELECT CASE Location
WHEN 1 then 'North'
WHEN 2 then 'South'
WHEN 4 then 'East'
WHEN 5 then 'West'
end as Locations, Name, Owes, Paid, OrigAmt, SubmitDate FROM Cure ", mySQLconnection);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
DataSet myDataSet = new DataSet();
mySqlAdapter.Fill(myDataSet);
ReportGrid.DataSource = myDataSet;
ReportGrid.DataBind();
if (mySQLconnection.State == ConnectionState.Open)
{
mySQLconnection.Close();
}
}
protected void ReportGrid_RowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[3].ForeColor = System.Drawing.Color.Green;
e.Row.Cells[2].ForeColor = System.Drawing.Color.Red;
}
Try adding a Locations column to your GridView control like this:
<asp:GridView runat="server" ID="ReportGrid" CssClass="table" AutoGenerateColumns="False"
AllowPaging="True" BorderColor="#E8CC6B" BorderStyle="Solid" BorderWidth="1px"
Width="100%" OnRowDataBound="ReportGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="Locations" HeaderText="Location" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Owes" HeaderText="Owes" />
<asp:BoundField DataField="Paid" HeaderText="Paid" />
<asp:BoundField DataField="OrigAmt" HeaderText="Amt" />
<asp:BoundField DataField="SubmitDate" DataFormatString="{0:MM/dd/yy}" HeaderText="Date" />
</Columns>
</asp:GridView>
There is no need to use an ASP.NET repeater if you add a bound field column to your GridView. Hope this helps.