delete row from gridview sql - c#

I want to be able to delete a row when I click on the delete button on that gridview. I have the aspx page and the code behind as well as the app code. The DeletePaymentCondition runs the store procedure to delete the row. But somehow the overall code doesnt work
aspx
<asp:GridView ID="gridview1" runat="server" HorizontalAlign="left" AutoGenerateColumns="false" CssClass="table table-bordered " GridLines="None"
AllowSorting="True" OnRowDeleting="OnRowDeleting">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="left" HeaderText="Payment Condition" HeaderStyle-CssClass="OGColor" HeaderStyle-ForeColor="white" SortExpression="monthToQuarters">
<ItemTemplate>
<span style="font-size:12px; color: #2980b9; text-align:left">
<asp:Label ID="lblUserId" runat="server" Visible="true" Text="<%# bind('payConditionId')%>"/>
</span>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150"/>
</Columns>
</asp:GridView>
cs
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lblEmpID = (Label)gridPayment.Rows[e.RowIndex].FindControl("lblUserId"); //This is Table Id load on Label1
int id = Convert.ToInt32(lblEmpID.Text.ToString());
dsPayment = objcommission.Delete(id);
gridPayment.DataSource = dsPayment.Tables[0];
gridPayment.DataBind();
}
app code
public DataSet DeletePayment(int id)
{
DataSet dsGetAllPayment;
dsGetAllPaymentCondition = SqlHelper.ExecuteDataset(OGconnection, CommandType.Text, "Delete FROM tblPay where pay ='" + id + "'");
return dsGetAllPayment;
}

You shoul execute two different SQL, one for the delete and a new select one to retreive the new data.
The DELETE should be executed using in a NonQuery because it does not return rows (only the number of rows affected).
public DataSet DeletePaymentCondition(int ids)
{
int rowsAffected = SqlHelper.ExecuteNonQuery(OGconnection, CommandType.Text, "Delete FROM [Accounting].[dbo].[tblPayConditions] where payConditionId ='" + ids + "'");
DataSet dsGetAllPaymentCondition = SqlHelper.ExecuteDataSet(OGconnection, CommandType.Text, "Select * FROM [Accounting].[dbo].[tblPayConditions]");
return dsGetAllPaymentCondition;
}
As a good praxys, you should consider changing it into parametrized queries. In this case it is safe because of the integer conversion, but in similar code with string parameters you would be prone to SQL Injection attacks

I got the solution. I've made changes to the cs file and as well as the code provided by bradbury9.
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(gridPaymentCondition.DataKeys[e.RowIndex].Value.ToString());
dsPaymentCondition = objcommission.DeletePaymentCondition(index);
gridPaymentCondition.DataSource = dsPaymentCondition.Tables[0];
updatePaymentConditionsWithoutRefresh();
}

Related

Access HyperLink inside ItemTemplate inside TemplateField ASP.Net WebForms

I have an ASP TemplateField inside a data populated GridView as follows:
<asp:GridView ID="gvReport" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" OnRowDataBound="gvReport_RowDataBound" CssClass="table table-bordered">
<Columns>
<asp:BoundField DataField="Delete" HeaderText="Delete" SortExpression="Delete" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:HyperLink runat="server" NavigateUrl='<%# "Edit?from=Delete&ID=" + Eval("ID") %>' ImageUrl="Assets/SmallDelete.png" SortExpression="PathToFile" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In other words, at the end of each row, there is a delete 'button'. I can tell whether a particular row/record has been deleted by checking the true/false value of the BoundField Delete in my code behind as follows:
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell statusCell = e.Row.Cells[0];
if (statusCell.Text == "True")
{
//change ImageUrl of Hyperlink for this row
}
}
Right now, my icon is red for delete, but in the case that a record has already been deleted,
I would like to change the image to a different icon (a blue one).
How can I change this ImageUrl if statusCell evaluates to true?
ok, so we will need two parts here:
We need (want) to persist the data table that drives the grid).
The REASON for this?
We kill about 3 birds with one stone.
We use the data table store/save/know the deleted state
We use that delete information to toggle our image
(and thus don't have to store the state in the grid view).
We ALSO then case use that table state to update the database in ONE shot, and thus don't have to code out a bunch of database operations (delete rows). We just send the table back to the database.
In fact in this example, I can add about 7 lines of code, and if you tab around, edit the data? It ALSO will be sent back to the database. And this means no messy edit templates and all that jazz (which is panful anyway).
Ok, so, here is our grid - just some hotels - and our delete button with image:
markup:
<div style="width:40%;margin-left:20px">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table table-hover borderhide" >
<Columns>
<asp:TemplateField HeaderText="HotelName" >
<ItemTemplate><asp:TextBox id="HotelName" runat="server" Text='<%# Eval("HotelName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName" SortExpression="ORDER BY FirstName" >
<ItemTemplate><asp:TextBox id="FirstName" runat="server" Text='<%# Eval("FirstName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName" >
<ItemTemplate><asp:TextBox id="LastName" runat="server" Text='<%# Eval("LastName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" >
<ItemTemplate><asp:TextBox id="City" runat="server" Text='<%# Eval("City") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="cmdDelete" runat="server" Height="20px" Style="margin-left:10px"
ImageUrl="~/Content/cknosel.png"
Width="24px" OnClick="cmdDelete_Click"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="cmdDeleteAll" runat="server" Text="Delete selected" Width="122px"
OnClientClick="return confirm('Delete all selected?')" />
</div>
Ok, and the code to load up the grid - NOTE WE persist the data table!!!!!
Code:
DataTable rstTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
else
rstTable = (DataTable)ViewState["rstTable"];
}
void LoadGrid()
{
// load up our grid
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
rstTable.Clear();
rstTable.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstTable;
GridView1.DataBind();
}
ViewState["rstTable"] = rstTable;
}
Ok, so far, real plain jane. The result is this:
Ok, so now all we need is to add the delete button click event.
That code looks like this:
protected void cmdDelete_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow rRow = (GridViewRow)btn.Parent.Parent;
DataRow OneRow = rstTable.Rows[rRow.DataItemIndex];
// toggle data
if (OneRow.RowState == DataRowState.Deleted)
{
// undelete
OneRow.RejectChanges();
btn.ImageUrl = "/Content/cknosel.png";
}
else
{
// delete
OneRow.Delete();
btn.ImageUrl = "/Content/ckdelete.png";
}
}
Again, really simple. But NOTE how we use the data table row state (deleted or not).
And this ALSO toggles the image for the delete button.
So, we don't have to care, worry, or store/save the sate in the grid.
So, if I click on a few rows to delete, I now get this:
So far - very little code!!!
Ok, so now the last part. the overall delete selected button. Well, since that is dangerous - note how I tossed in a OnClientClick event to "confirm the delete. if you hit cancel, then of course the server side event does not run.
But, as noted since we persisted the table? Then we can send the table deletes right back to the server without a loop. The delete code thus looks like this:
protected void cmdDeleteAll_Click(object sender, EventArgs e)
{
// send updates (deletes) back to database.
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotels WHERE ID = 0",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
SqlDataAdapter daUpdate = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daUpdateBuild = new SqlCommandBuilder(daUpdate);
daUpdate.Update(rstTable);
}
LoadGrid(); // refesh display
}
So, note how easy it is to update (delete) from the database. If you look close, I used text boxes for that grid - not labels. The reason of course is that if the user tabs around in the grid (and edits - very much like excel), then I can with a few extra lines of code send those changes back to the database. In fact the above delete button code will be 100% identical here (it will send table changes back with the above code. So, if we add rows, edit rows then the above is NOT really a delete command, but is in fact our save edits/deletes/adds command!

Asp.Net C# Delete row from dataTable gridview on button click

I'm displaying a datatable that selects a number of elements from the database (IncomingsId, Type, Cost, Frequency) and I'm not sure how to delete a row when a button is clicked.
I've tried many solutions so far but nothing is working.
Here is the button I have within my Grid view
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:button id="DeleteRowButton" text="Delete Record" onclick="DeleteRowButton_Click" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
And here is the code behind this page were I am creating the datatable.
SqlConnection con;
public _Default()
{
con = new SqlConnection(#"MySQLConnection");
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayRecord();
}
}
public DataTable DisplayRecord()
{
string userId = (HttpContext.Current.User.Identity.GetUserId());
SqlDataAdapter Adp = new SqlDataAdapter("select * from Incomings where AspNetUsersId = '" + userId +"'", con);
DataTable Dt = new DataTable();
Dt.AcceptChanges();
Adp.Fill(Dt);
grid1.DataSource = Dt;
grid1.DataBind();
return Dt;
}
public void DeleteRowButton_Click(object sender, EventArgs e)
{
}
Cheers in advance for any help. I'm sure it's a simple resolution
You need a way for your code to know which ID to delete. Here is how I would normally do it:
Replace your button with an ItemTemplate, and add the button in here instead:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Delete" runat="server" CommandArgument='<%# Eval("userId") %>' CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
When you have the button this way, you now have access to a CommandArgument and CommandName attributes. Notice the argument I am passing is Eval("userId"), the command name (as you will see later) is used to recognize what action you want to execute (this could be anything, is just a name).
Replace the CommandArgument with whatever value(s) you want to pass to the server, using the name that came from the database/datasource (I am guessing it would be userId).
Then, to capture this you need to implement the RowCommand event of the GridView, and intercept the correct CommandName:
public void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string userId = e.CommandArgument.ToString();
//do something with the id
}
}
Here you have to make sure the CommandName in your button, matches to whatever action you want to execute in the RowCommand. This should do the trick.
Don't forget to bind the event to your GridView:
<asp:GridView OnRowCommand="GridView1_RowCommand" ID="GridView1" runat="server">
...
</asp:GridView>
just use this for the front-end code
<asp:GridView ID="grid1" OnRowDeleting="OnRowDeleting" DataKeyNames="deleteR" runat="server" AutoGenerateColumns="False" CellPadding="4" GridLines="None" style="width:100%" >
<columns>
<asp:TemplateField HeaderText="Delete Row">
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" class="btn btn-primary" Text="Delete" CommandName="Delete" OnRowDataBound="OnRowDataBound" />
</ItemTemplate>
</asp:TemplateField>
And have this in behind it:
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int deleteR= Convert.ToInt32(grid1.DataKeys[e.RowIndex].Values[0]);
//have a sql statement here that add's the parameter ID for the row you want to delete, something like
SqlCommand com = new SqlCommand ("Delete FROM yourdatabase Where yourID = #yourID"
com.Parameters.AddWithValue("#yourID", yourID)
}
What you're looking for is indeed a simple solution.
You can use a foreach loop to search all DataRows within the DataTable for some kind of ID.Here's an example of what I mean:
String s = "/* IncomingsId for what you want to delete */";
foreach (DataRow r in dt.Rows) {
if (r["IncomingsId"].ToString().Equals(s)) {
dt.Rows.Remove(r);
}
}
Just a quick update for anyone that's helped me, thanks for your advice.
Asp.Net has it's own built in AutoGenerateDeleteButton and I set that to true and ran a bit of code behind it.
A simple solution that really shouldn't have taken me all day to complete!

Need to add a hyperlinkfield to a gridview containing data from another column

I have a gridview that gets data from an sqldatasource and as a results gets 3 columns from an SQL query: ID, description and price.
What I want to do is adding another column with an hyperlink in the format of page.aspx?id=x where x is the ID code from the first column. This for each row in the table.
I've been looking all morning for how to do this, all I got is that I have to manage the RowDataBound event and use an hyperlinkfield but couldn't find anything else that explained how they actually work together, even the msdn article is kind of vague on the subject or just doesn't have any relevant help for my specific case as I'm managing the gridview from the code-behind.
Also haven't been able to figure how to access strings from the other columns, since it's what I need to insert in the resulting hyperlink.
Here's what I got so far for the creation of the gridview:
private void FillGrid(string qid)
{
SqlDataSource1.ConnectionString = Connessione.connectionString;
SqlDataSource1.SelectCommand = "SELECT art_tessuto_articolo, art_tessuto_descrizione, lipre_prezzo FROM lipre INNER JOIN listini_tessuti ON lipre.lipre_codice = listini_tessuti.listini_codice INNER JOIN art_tessuti ON lipre.lipre_articolo = art_tessuti.art_tessuto_articolo WHERE lipre_codice = #qid AND lipre_prezzo <> 0";
SqlDataSource1.SelectParameters.Clear();
SqlDataSource1.SelectParameters.Add("qid", qid);
GridView1.AllowPaging = true;
GridView1.PageSize = 500;
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
This should do the job.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlControl = new HyperLink();
hlControl.Text = e.Row.Cells[0].Text;
hlControl.NavigateUrl = "page.aspx?id=" + e.Row.Cells[0].Text;
e.Row.Cells[3].Controls.Add(hlControl);
}
}
Use HyperlinkField
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:HyperlinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="page.aspx?ID={0}" />
</Columns>
</asp:GridView>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" Text="VisibleText" NavigateUrl='<%# Eval(columnname) %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Paging DataGrid Data using C#, Prev/Next don't work

Okay, I have looked everywhere and tried almost every suggestion that I could find and NOTHING has worked so far. D: Here's my problem:
I have a DataGrid with TemplateItemsthat the user has enteres into two TextBoxes that populates with data after the click of a button. My button takes two dates that the user enteres into two TextBoxes and pulls all entries between those dates from a DataBase. The entries are then displayed in the DataGrid. What I need this DataGrid to do is allow paging with 10 rows per page. All I need are Next and Prev links to go through the pages that contain data. The links work but the data doesn't change (Next doesn't go to the next page, the data remains the same). I know for a fact that there are more than 10 entries for Items between certain dates so I know the data should change based on what page it's on. Also, the Next buttons seems to be infinite. Why? Someone, please help me.
Now for some reason, when I get the data from the database, it starts out by getting all entries but then it only stores 10 (which is the amount that I want the pages to display at a time). The data never shows the rest that there should be... Why?! D':
Set New Page Index before you set datasource.
protected void dgArchive_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
if (source != null)
{
dgArchive.CurrentPageIndex = e.NewPageIndex;
JSP_Extrusion_QCEntities ent = new JSP_Extrusion_QCEntities(ConfigurationManager.ConnectionStrings["QCConnString"].ToString());
DateTime start = Convert.ToDateTime(Start.Text);
DateTime end = Convert.ToDateTime(End.Text).AddDays(1);
AllDataSources ds = new AllDataSources();
dgArchive.DataSource = ds.populateArchive(ent, start, end);
dgArchive.DataBind();
}
}
Also, why do you wire up your events on Page_Load? You don't need to do that if you do it on the markup.
These 3 lines:
GetDateEntries.Click += new EventHandler(GetDateEntries_Click);
dgArchive.VirtualItemCount = 200;
dgArchive.PageIndexChanged += new DataGridPageChangedEventHandler(dgArchive_PageIndexChanged);
Should be declared in the markup. Here's how you register on PageIndexChanged for your grid from the markup.
<asp:DataGrid ID="dgArchive" CssClass="data" AutoGenerateColumns="False" runat="server" AllowPaging="true"
PageSize="10" EnableViewState="true" AllowCustomPaging="true" Visible="false"
OnPageIndexChanged="dgArchive_PageIndexChanged"
>
Here's an example from MSDN.
You need to rebind the grid each time you change the page. Here's an example that outlines what you need to do:
<asp:DataGrid ID="DataGrid1" runat="server" OnPageIndexChanged="DataGrid1_PageIndexChange" ...>
Code-behind:
protected void DataGrid1_PageIndexChange(object sender, DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
BindDataGrid();
}
private void BindDataGrid()
{
DataGrid1.DataSource = GetSomeData();
DataGrid1.DataBind();
int total = dt.Rows.Count;
int pSize = grdJobs.PageSize;
int pIndex = grdJobs.CurrentPageIndex;
if (total < pSize)
pSize = total;
int start = (pSize * pIndex) + 1;
int end = (start + pSize) - 1;
if (end > total)
end = total;
lblTotalResults.Text = String.Format("Displaying {0}-{1} Of {2}", start, end, total);
}
So one of my co-workers ended up helping me with this one. Okay! This is the final result of my paging DataGrid. All of this code allowed me to get the number of items pulled from the database, set the VirtualItemCount (which also sets the number of pages that display), and page through the data. Please note that AllDataSources is a separate class that just pulls the data from the database in a way that works with my grid's set-up and CamSizerData is the name of the Table that contains all the data and is used to get the Count. If you have any other questions, please feel free to ask. :)
DataGrid
<asp:DataGrid ID="dgArchive" CssClass="data" AutoGenerateColumns="False" runat="server"
AllowPaging="True" AllowCustomPaging="True" Visible="False" OnPageIndexChanged="dgArchive_PageIndexChanged">
<Columns>
<asp:TemplateColumn HeaderStyle-CssClass="infoHeaderDG" ItemStyle-CssClass="line">
<HeaderTemplate>
Line</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="LineNumber" Text='<%# DataBinder.Eval(Container.DataItem, "LineNumber") %>'
runat="server" /></ItemTemplate>
<HeaderStyle CssClass="infoHeaderDG"></HeaderStyle>
<ItemStyle CssClass="line"></ItemStyle>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderStyle-CssClass="infoHeaderDG" ItemStyle-CssClass="date">
<HeaderTemplate>
Date</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="CreateDate" Text='<%# DataBinder.Eval(Container.DataItem, "CreateDate", "{0: MM/dd/yyyy}") %>'
runat="server" /></ItemTemplate>
<HeaderStyle CssClass="infoHeaderDG"></HeaderStyle>
<ItemStyle CssClass="date"></ItemStyle>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderStyle-CssClass="infoHeaderDG" ItemStyle-CssClass="operator">
<HeaderTemplate>
Operator</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Operator" Text='<%# DataBinder.Eval(Container.DataItem, "Operator") %>'
runat="server" /></ItemTemplate>
<HeaderStyle CssClass="infoHeaderDG"></HeaderStyle>
<ItemStyle CssClass="operator"></ItemStyle>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderStyle-CssClass="infoHeaderDG" ItemStyle-CssClass="product">
<HeaderTemplate>
Product</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Product" Text='<%# DataBinder.Eval(Container.DataItem, "ProdNumber") %>' runat="server" /></ItemTemplate>
<HeaderStyle CssClass="infoHeaderDG"></HeaderStyle>
<ItemStyle CssClass="product"></ItemStyle>
</asp:TemplateColumn>
</Columns>
<PagerStyle Mode="NumericPages" PageButtonCount="5" />
</asp:DataGrid>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
Page.MaintainScrollPositionOnPostBack = true;
}
protected void GetDateEntries_Click(object sender, EventArgs e)
{
dgArchive.Visible = true;
using (Entities ent = new Entities(ConfigurationManager.ConnectionStrings["QCConnString"].ToString()))
{
DateTime start = Convert.ToDateTime(Start.Text);
DateTime end = Convert.ToDateTime(End.Text).AddDays(1);
AllDataSources ds = new AllDataSources();
CamsizerData cd = new CamsizerData();
IEnumerable<CamsizerData> led = cd.GetBySelectedDates(ent, start, end);
int counter = led.Count();
dgArchive.VirtualItemCount = counter;
dgArchive.DataSource = ds.populateArchive(ent, start, end);
dgArchive.DataBind();
}
}
protected void dgArchive_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
if (source != null)
{
dgArchive.CurrentPageIndex = e.NewPageIndex;
Entities ent = new Entities(ConfigurationManager.ConnectionStrings["QCConnString"].ToString());
DateTime start = Convert.ToDateTime(Start.Text);
DateTime end = Convert.ToDateTime(End.Text).AddDays(1);
AllDataSources ds = new AllDataSources();
IEnumerable<object> recs = ds.populateArchive(ent, start, end);
dgArchive.DataSource = recs.Skip(10 * e.NewPageIndex);
dgArchive.DataBind();
}
}

Changing values inside my GridView on load with ASP.NET

I have a GridView that gets populated with data from a SQL database, very easy.
Now i want to replace values in my one column like so......
If c04_oprogrs value is a 1 then display Take in the GridView.
If c04_oprogrs value is 2 then display Available in the GridView.
What code changes must i make to change to my code to display the new values.
My Grid
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="281px" Width="940px"
Font-Size="X-Small" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="c04_oprogrs" HeaderText="Order Progress"
SortExpression="c04_oprogrs" />
<asp:BoundField DataField="c04_orderno" HeaderText="Order No."
SortExpression="c04_orderno" />
<asp:BoundField DataField="c04_orddate" HeaderText="Date of Order"
SortExpression="c04_orddate" DataFormatString="{0:d/MM/yyyy}" />
<asp:BoundField DataField="c04_ordval" HeaderText="Order Value"
SortExpression="c04_ordval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_delval" HeaderText="Delivered Value"
SortExpression="c04_delval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_invval" HeaderText="Invoice Value"
SortExpression="c04_invval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_orddesc" HeaderText="Order Description"
SortExpression="c04_orddesc" >
<ControlStyle Width="300px" />
</asp:BoundField>
</Columns>
</asp:GridView>
My Page load
SqlConnection myConnection;
DataSet dataSet = new DataSet();
SqlDataAdapter adapter;
//making my connection
myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SAMRASConnectionString"].ConnectionString);
adapter = new SqlDataAdapter("Select TOP 40 c04_credno, c04_orderno, c04_orddate, c04_ordval, c04_delval, c04_invval, c04_oprogrs, c04_orddesc FROM C04ORDS WHERE c04_credno = '" + Session["CreditorNumber"] + "'AND c04_oprogrs <> 9 ORDER BY c04_orddate DESC", myConnection);
adapter.Fill(dataSet, "MyData");
GridView1.DataSource = dataSet;
Session["DataSource"] = dataSet;
GridView1.DataBind();
Etienne
EDIT:
MY FINAL SOLUTION
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Find the value in the c04_oprogrs column. You'll have to use
string value = e.Row.Cells[0].Text;
if (value == "1")
{
e.Row.Cells[0].Text = "Take";
}
else if (value == "2")
{
e.Row.Cells[0].Text = "Available";
}
}
}
You can use the RowDataBound event for this. Using this event you can alter the content of specific columns before the grid is rendered.
To clarify a little. First you add a template column with a label to your grid view (see also the answer by ranomore):
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="myLabel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Next you implement the RowDataBound event (I haven't checked the code below, so it may contain some syntax errors):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Find the value in the c04_oprogrs column. You'll have to use
// some trial and error here to find the right control. The line
// below may provide the desired value but I'm not entirely sure.
string value = e.Row.Cells[0].Text;
// Next find the label in the template field.
Label myLabel = (Label) e.Row.FindControl("myLabel");
if (value == "1")
{
myLabel.Text = "Take";
}
else if (value == "2")
{
myLabel.Text = "Available";
}
}
}
You could use a template column and call a function in your code behind.
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text='<%#FieldDisplay(Eval("c04_oprogrs")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
then in your code behind do
protected string FieldDisplay(int c04_oprogrs)
{
string rtn = "DefaultValue";
if (c04_oprogrs == 1)
{
rtn = "Take";
}
else if (c04_oprogrs == 2)
{
rtn = "Available";
}
return rtn;
}
Without using a function. The ternary statement is in VB. If you have to nest another ternary statement to really test for 2 then it'd be easier to go with rwwilden's solution.
<asp:TemplateField HeaderText="Order Progress" SortExpression="c04_oprogrs" >
<ItemTemplate>
<asp:Label runat="server" ID="Label1" Text='<%# IIF(CInt(Eval("c04_oprogrs")) = 1, "Take", "Available") %>' />
</ItemTemplate>
</asp:TemplateField>
You could add a field in the SQL Statement
adapter = new SqlDataAdapter("Select TOP 40 c04_credno, c04_orderno, c04_orddate,
c04_ordval, c04_delval, c04_invval, c04_oprogrs, c04_orddesc ,
CASE c04_oprogrs WHEN 1 THEN "Take" WHEN 2 THEN "Available" ELSE "DontKnow" END AS
Status FROM C04ORDS WHERE c04_credno = '" + Session["CreditorNumber"] + "'AND
c04_oprogrs 9 ORDER BY c04_orddate DESC", myConnection);
And make that new field part of the BoundColumn in the markup.
Pardon my SQL syntax but I hope you get the idea.
EDIT: Do not use the syntax = '" + Session["CreditorNumber"] + "'.
See sql injection attack and how to avoid it using parameterized SQL.
This is the best efficient way.
Make a case in sql server view, like :-
select case <columnname>
when 1 then 'available'
when 0 then 'not available'
end as <columnname>
from <tablename>

Categories