SQL Server stored procedure accepts the parameters, current company name, new company name and whether it already exists which has a default value. When the edit button is clicked on the front end UI, the grid view allows me to edit the company name. This shows an 'Update' button - when this is clicked - the code parses however nothing updates and company name does not update either.
Breakpoint is set and stepped through and #CurrentCompanyName is returned as null. Not sure how to fix this.
Aspx:
<asp:GridView ID="CompanyTable" runat="server"
OnRowEditing="CompanyTable_RowEditing"
OnRowCancelingEdit="CompanyTable_RowCancelingEdit"
OnRowUpdating="CompanyTable_RowUpdating"
OnPageIndexChanging="CompanyTable_PageIndexChanging"
PageSize="20" Font-Underline="False" AllowPaging="True">
<HeaderStyle Width="150px" />
<Columns>
<asp:TemplateField>
<HeaderStyle Width="200px" />
<ControlStyle CssClass="ButtonDesigntwo" />
<ItemTemplate>
<asp:LinkButton ID="Edit" ButtonType="Button" runat="server" CommandName="Edit" Text="Edit" />
<asp:LinkButton ID="Delete" ButtonType="Button" runat="server" CommandName="Delete" Text="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="Update" ButtonType="Button" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="Cancel" ButtonType="Button" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="tableHeaderStyle" />
<PagerSettings Mode="NumericFirstLast" />
<PagerStyle CssClass="pager" BorderColor="Black" ForeColor="White" Font-Underline="False" />
<RowStyle CssClass="tableRowStyle" />
</asp:GridView>
Method code:
protected void CompanyTable_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand("[updateCompanyName]", cn))
{
TextBox name = CompanyTable.Rows[e.RowIndex].FindControl("CompanyTable") as TextBox;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CurrentCompanyName", name);
cmd.Parameters.AddWithValue("#NewCompanyName", CompanyInputTextBox.Text).Direction = ParameterDirection.Input;
SqlParameter objisExists = new SqlParameter("#isExists", SqlDbType.Int);
objisExists.Direction = ParameterDirection.Output;
cmd.Parameters.Add(objisExists);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
int isExists = Convert.ToInt32(cmd.Parameters["#isExists"].Value.ToString());
if (isExists == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "111", "AddCompanyUpdating();", true);
}
else if (isExists == 1)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "111", "CompanyNotUpdatedValidation();", true);
}
}
// Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
CompanyTable.EditIndex = -1;
// Call ShowData method for displaying updated data
BindData();
}
Stored procedure:
ALTER PROCEDURE [dbo].[updateCompanyName]
#CurrentCompanyName VARCHAR(50),
#NewCompanyName VARCHAR(50),
#IsExists INT = 0 OUT
AS
BEGIN
DECLARE #CompanyID INT
SELECT #CompanyID = CompanyID
FROM company
WHERE companyname = #CurrentCompanyName
BEGIN
IF EXISTS (SELECT CompanyName
FROM company
WHERE companyname = #NewCompanyName )
BEGIN
SET #IsExists = 1
END
ELSE
BEGIN
UPDATE COMPANY
SET CompanyName = #NewCompanyName
WHERE companyid = #CompanyID
SET #IsExists = 0
END
END
PRINT #isexists
END
You are defining name as a textbox in this line:
TextBox name = CompanyTable.Rows[e.RowIndex].FindControl("CompanyTable") as TextBox;
Then you try to set the value of your parameter to the textbox in this line:
cmd.Parameters.AddWithValue("#CurrentCompanyName", name);
When what you SHOULD be doing, is setting the parameter value to the TEXT that is IN the textbox:
cmd.Parameters.AddWithValue("#CurrentCompanyName", name.Text);
EDIT:
Since name itself is NULL when you are hovering over it, that means that you have not correctly defined it in this line:
TextBox name = CompanyTable.Rows[e.RowIndex].FindControl("CompanyTable") as TextBox;
Stop the code in the debugger and open a quick view into CompanyTable, and see if you can figure out the correct way to define the textbox you are looking for.
EDIT 2: In defining your TextBox, you are doing FindControl("CompanyTable"), but according to your markup, "CompanyTable" is the ID of your GridView, not a textbox. In fact, I don't see any markup anywhere for a textbox in the first code sample you posted.
Related
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();
}
In below datalist represents set of question's and answer.
How to insert the user selected right answer radio button value into database when the user clicks on Final submit button?
<asp:DataList ID="DataList1" runat="server" DataSourceID="AccessDataSource1" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal" onselectedindexchanged="rd_CS_CheckedChanged">
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<AlternatingItemStyle BackColor="#F7F7F7" />
<ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<ItemTemplate>
Q:
<asp:Label ID="QLabel" runat="server" Text='<%# Eval("Q") %>' />
<br />
A:
<asp:RadioButton ID="rd_CS" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("A") %>'></asp:RadioButton>
<br />
B:
<asp:RadioButton ID="rd_CS2" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("B") %>'></asp:RadioButton>
<br />
C:
<asp:RadioButton ID="rd_CS3" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("C") %>'></asp:RadioButton>
<br />
D:
<asp:RadioButton ID="rd_CS4" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("D") %>'></asp:RadioButton>
<p style="color: #FF3300">
<asp:Label ID="Correct_AnswerLabel" runat="server"
Text='<%# Eval("Correct_Answer") %>' Visible="False" /></p>
</ItemTemplate>
<SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
</asp:DataList>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/Quize.mdb"
SelectCommand="SELECT [Q],[A], [B], [C], [D], [Correct Answer] AS Correct_Answer FROM [QuizData]">
</asp:AccessDataSource>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
In Button1_Click on your codebehind you can improve this method:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
RadioButton rd_CS = (RadioButton)item.FindControl("rd_CS");
RadioButton rd_CS2 = (RadioButton)item.FindControl("rd_CS2");
RadioButton rd_CS3 = (RadioButton)item.FindControl("rd_CS3");
RadioButton rd_CS4 = (RadioButton)item.FindControl("rd_CS4");
if (rd_CS.Checked)
{
Insert(rd_CS.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS2.Checked)
{
Insert(rd_CS2.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS3.Checked)
{
Insert(rd_CS3.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS4.Checked)
{
Insert(rd_CS4.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
}
}
And the Insert function definition will be same as:
private void Insert(string value)
{
//Your code here to save on database
OleDbConnection connection = new OleDbCommand("Your sql connection String");
OleDbCommand command = new OleDbCommand("Your sql insert query");
command.Connection = connection;
//ParĂ¡meters of command
OleDbParameter param = new OleDbParameter("Parameter name and next your type", OleDbType.VarChar);
param.Value = value;
command.Parameters.Add(param);
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
//Your value is saved now
}
This is how you can save all checked radiobutton on datalist you asked
This is my codebehind .When i click on button then Repeated selected radio button values are save in my database . this is my problem. I need only unique value in my database
protected void rd_CS_CheckedChanged(object sender, EventArgs e)
{
string myRadioText = String.Empty;
foreach (DataListItem item in DataList1.Items)
{
RadioButton rd_CS = (RadioButton)item.FindControl("rd_CS");
RadioButton rd_CS2 = (RadioButton)item.FindControl("rd_CS2");
RadioButton rd_CS3 = (RadioButton)item.FindControl("rd_CS3");
RadioButton rd_CS4 = (RadioButton)item.FindControl("rd_CS4");
if (rd_CS != null && rd_CS.Checked)
{
myRadioText = rd_CS.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS2 != null && rd_CS2.Checked)
{
myRadioText = rd_CS2.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS3 != null && rd_CS3.Checked)
{
myRadioText = rd_CS3.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS4 != null && rd_CS4.Checked)
{
myRadioText = rd_CS4.Text;
Label1.Text = myRadioText.ToString();
}
string str = Server.MapPath("~/App_Data/Quize.mdb");
OleDbConnection ole = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str + ";Persist Security Info=True");
ole.Open();
OleDbCommand cmd = new OleDbCommand("insert into Userdata values ('" + Label1.Text.Trim().Replace("'", "''") + "','" + Label1.Text.Trim().Replace("'", "''") + "',)", ole);
cmd.ExecuteNonQuery();
}
I have an asp.net web forms application which when a user tabs out of the username field it checks my database to see if its available or not but the issue I am having is that it always seems to fall into the exists even if it doesn't.
I have watched many videos on it and also read many articles but I can't get it to work at all.
I have provided all my code below.
Config
<add name="PaydayLunchConnectionString1" connectionString="Data Source=********\*******;Initial Catalog=************;Integrated Security=True"
providerName="System.Data.SqlClient" />
HTML
<asp:GridView ID="tblUsers" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlUsers" GridLines="None" Width="15%">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
</asp:GridView>
<asp:SqlDataSource ID="SqlUsers" runat="server" ConnectionString="<%$ ConnectionStrings:PaydayLunchConnectionString1 %>" SelectCommand="SELECT [Name] FROM [Users] WHERE [name] != 'Admin'"></asp:SqlDataSource>
<asp:Label ID="removeUserNotExist" runat="server" Text="The user entered does not exist. Please try again." Visible="false" style="color: red"></asp:Label>
<asp:Label ID="removeUserExists" runat="server" Text="The user entered exists." Visible="false" style="color: green"></asp:Label>
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="txtRemoveUser" CssClass="col-sm-offset-2 col-sm-3 control-label">Enter Name To Be Removed</asp:Label>
<div class="col-sm-3">
<asp:TextBox runat="server" ID="txtRemoveUser" CssClass="form-control" AutoPostBack="true" OnTextChanged="txtRemoveUser_TextChanged" />
</div>
</div>
Code Behind
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
protected void txtRemoveUser_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtRemoveUser.Text))
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Name != #Name", conn);
cmd.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
removeUserNotExist.Visible = true;
removeUserExists.Visible = false;
}
else
{
removeUserNotExist.Visible = false;
removeUserExists.Visible = true;
}
}
}
DB Details
Table Name = Users
Columns = ID, Name, Password
Users = Test, Test2
If I enter 'Test' in the field and tab out, I get the correct message (Exists) but if i then enter 'ABC' I still get the 'Exists' message.
If there is more than 1 user in your database, this query will always produce rows. Hence, your if statement always produces the same result:
SELECT * FROM Users WHERE Name != #Name
If you want to check if a user name exists, simply check for equality.
SELECT * FROM Users WHERE Name = #Name
If that one returns a row, the user name exists. Otherwise it doesn't.
A better solution would be to use 1 in the select, since that prevents the database to return all row data, a small performance improvement:
SELECT 1 dummy FROM Users WHERE Name = #Name
I have a gridview which contains textboxes and dropdowns.In gvScheduleBattingScore_RowDataBound Event I am binding dropdowns without any problem. The button control is outside to the gridview. I actually want to submit all the textbox values and dropdown selected values to the database on buttonclickevent But I don't know where I am going wrong.
The Problem is Textboxes do not contain any text and am getting Exception
Input string was not in a correct format.
Please help me out...
<asp:GridView ID="gvScheduleBattingScore" runat="server" AllowSorting="false" AutoGenerateColumns="False" AllowPaging="false"
GridLines="None" CellPadding="1" CssClass="GridViewStyle" ShowFooter="false" width="100%"
OnRowDataBound="gvScheduleBattingScore_RowDataBound">
<Columns>
<asp:BoundField DataField="P_PlayerId" HeaderText="Player Id" HeaderStyle-Wrap="true" HeaderStyle-Width="5%" Visible="false"/>
<asp:BoundField DataField="PlayerName" HeaderText="Player Name" HeaderStyle-Wrap="true" HeaderStyle-Width="30%"/>
<asp:TemplateField HeaderText="Playing Order" HeaderStyle-Wrap="true" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:TextBox ID="txtPlayingOrder" runat="server" CssClass="TinyTexBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:TextBox ID="txtStatus" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bold By">
<ItemTemplate>
<asp:DropDownList ID="ddlBoldBy" runat="server"> </asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</br>
<asp:Button ID="ButtonAdd" runat="server" Text="Add" CssClass="SmallButton"
ValidationGroup="Add" onclick="ButtonAdd_Click"/>
On ButtonClick Event:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlConnection dBConnection = null;
try
{
int playerId;
short plyerOrder;
string BatsmanStatus;
int boldBy;
dBConnection = new SqlConnection();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["CriConn"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_InsertScores", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
foreach (GridViewRow GVRow in gvScheduleBattingScore.Rows)
{
string textPlayerId = GVRow.Cells[0].Text;
TextBox textPlyerOrder = (TextBox)GVRow.Cells[1].FindControl("txtPlayingOrder");
TextBox textBatsmanStatus = GVRow.Cells[2].FindControl("txtStatus") as TextBox;
DropDownList DropDownBoldBy = (DropDownList)GVRow.Cells[18].FindControl("ddlBoldBy");
playerId = Convert.ToInt32(textPlayerId );
if (!string.IsNullOrEmpty(textPlyerOrder.Text))
plyerOrder = Convert.ToInt16(textPlyerOrder.Text);
if (!string.IsNullOrEmpty(textBatsmanStatus.Text))
BatsmanStatus = textBatsmanStatus.Text;
if (!string.IsNullOrEmpty(DropDownBoldBy.SelectedValue) && DropDownLbwBy.SelectedValue != "Select")
boldBy = Convert.ToInt32(DropDownBoldBy.SelectedValue);
cmd.Parameters.Add("#PlayerId", SqlDbType.NVarChar).Value = playerId;
cmd.Parameters.Add("#PlayerId", SqlDbType.Int).Value = playerId;
cmd.Parameters.Add("#plyerOrder", SqlDbType.Int).Value = plyerOrder;
cmd.Parameters.Add("#BatsmanStatus", SqlDbType.NVarChar).Value = BatsmanStatus;
dBConnection.Open();
dataAdapter.InsertCommand = cmd;
cmd.ExecuteNonQuery();
dBConnection.Close();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close data reader object and database connection
cmd.Dispose();
cmd = null;
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
As per the Chat discussion with #bhoopendra.sahoo, we come to the conclusion that it is a Binding issue.
When Button Click Event is fired, the GridView binds again causing the issue.
The fix is to bind the GridView only once and restrict its binding during other events.
Add a null checking before converting the textbox value to int
if (!string.IsNullOrEmpty(textPlayerId.Text))
playerId = Convert.ToInt32(textPlayerId);
Also make these changes to you code, to find the textbox controls in the correct cell
TextBox textPlyerOrder = (TextBox)GVRow.Cells[2].FindControl("txtPlayingOrder");
TextBox textBatsmanStatus = (TextBox)GVRow.Cells[3].FindControl("txtStatus");
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>