I have a gridview and detailsview in my aspx page and using object data source to display data, the primary key on the table is consist of 2 columns, so I set DataKeyNames = "ID,StepCount" in Gridview1, see my web page code below:
<asp:GridView ID="GridView1" DataKeyNames="ID,StepCount" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="StepCount" HeaderText="StepCount" SortExpression="StepCount" />
<asp:BoundField DataField="Direction" HeaderText="Direction" SortExpression="Direction" />
<asp:BoundField DataField="StatusChangeTo" HeaderText="StatusChangeTo" SortExpression="StatusChangeTo" />
</Columns>
</asp:GridView>
<br />
<asp:DetailsView ID="DetailsView1" DataKeyNames="ID,StepCount" runat="server" Height="50px" Width="125px" AutoGenerateRows="False"
DataSourceID="ObjectDataSource2">
<Fields>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="StepCount" HeaderText="StepCount" SortExpression="StepCount" />
<asp:BoundField DataField="Direction" HeaderText="Direction" SortExpression="Direction" />
<asp:BoundField DataField="StatusChangeTo" HeaderText="StatusChangeTo" SortExpression="StatusChangeTo" />
<asp:BoundField DataField="TicketID" HeaderText="TicketID" SortExpression="TicketID" />
<asp:BoundField DataField="StandaloneIncident" HeaderText="StandaloneIncident" SortExpression="StandaloneIncident" />
<asp:BoundField DataField="CETransactionXML" HeaderText="CETransactionXML" SortExpression="CETransactionXML" />
</Fields>
</asp:DetailsView>
<br />
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="getAllMastterChildren"
TypeName="HarnessMaintain.Pages.DataAccessLayer"></asp:ObjectDataSource>
<br />
<asp:ObjectDataSource ID="ObjectDataSource2" runat="server" SelectMethod="getMasterchildByPK"
TypeName="HarnessMaintain.Pages.DataAccessLayer">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="ID" PropertyName="SelectedValue"
Type="Int32" />
<asp:ControlParameter ControlID="GridView1" Name="StepCount" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
following is my C# code to retrieve data according to choosed id and stepcount from Gridview:
public static List<MasterChildDetail> getMasterchildByPK(int ID, int StepCount)
{
string sqlStr = "select * from mswscemasterchild where id = :id and step_count = :step_count";
List<MasterChildDetail> mcds = new List<MasterChildDetail>();
MasterChildDetail mcd = new MasterChildDetail();
using (OracleConnection ocon = new OracleConnection(conStr))
{
OracleCommand ocmd = new OracleCommand(sqlStr, ocon);
ocmd.Parameters.Add(":id", ID);
ocmd.Parameters.Add(":step_count", StepCount);
ocmd.Connection.Open();
OracleDataReader reader = ocmd.ExecuteReader();
while (reader.Read())
{
mcd.ID = Convert.ToInt32(reader["ID"]);
mcd.StepCount = Convert.ToInt32(reader["STEP_COUNT"]);
if (System.DBNull.Value.Equals(reader["DIRECTION"]))
{
mcd.Direction = null;
}
else
{
mcd.Direction = reader["DIRECTION"].ToString();
}
if (System.DBNull.Value.Equals(reader["STATUS_CHANGE_TO"]))
{
mcd.StatusChangeTo = null;
}
else
{
mcd.StatusChangeTo = reader["STATUS_CHANGE_TO"].ToString();
}
if (System.DBNull.Value.Equals(reader["TICKET_ID"]))
{
mcd.TicketID = null;
}
else
{
mcd.TicketID = reader["TICKET_ID"].ToString();
}
if (System.DBNull.Value.Equals(reader["STANDALONE_INCIDENT"]))
{
mcd.StandaloneIncident = null;
}
else
{
mcd.StandaloneIncident = reader["STANDALONE_INCIDENT"].ToString();
}
if (System.DBNull.Value.Equals(reader["CE_TRANSACTION_XML"]))
{
mcd.CETransactionXML = null;
}
else
{
mcd.CETransactionXML = reader["CE_TRANSACTION_XML"].ToString();
}
mcds.Add(mcd);
break;
}
}
return mcds;
}
by debugging, I found a wired issue, the value of passed ID and StepCount are always exactly the same, even though I click on the second "Select" and the third "Select", see below:
can you tell me why or how to fix this issue?
The primary key column of your database is your DataKey name. And you can't have 2 primary keys in 1 table. So there should be only 1 column in GridView's DataKey name.
Related
I have a GridView with a sql Source, which is bound to a searchbox. The problem is that on Postback the GridView disappears. I have tried to DataBind the GridView in the PageLoad event but the problem is that the Data is coming from the searchbox so On Postback it takes out the value of the Searchbox and searches for it.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Archiv.aspx.cs" Inherits="AutoVerwaltungASP.Archiv" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:TextBox id="searchbox" Value="Search..." runat="server" ForeColor="Gray" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" />
<asp:Button Text="Suchen" runat="server" ID="btnSearch" OnClick="btnSearch_Click" Height="34px" Width="90px" Font-Size="Small"/>
<asp:Button Text="Reset" runat="server" ID="btnClear" OnClick="btnClear_Click" Height="34px" Width="90px" Font-Size="Small"/>
<cc1:AutoCompleteExtender ServiceMethod="markensuchen"
MinimumPrefixLength="2"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="searchbox"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
</cc1:AutoCompleteExtender>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataSourceID="SqlDataSourceAutos" ForeColor="Black" GridLines="Vertical" DataKeyNames="m_id" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="m_id" HeaderText="m_id" SortExpression="m_id" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="m_name" HeaderText="m_name" SortExpression="m_name" />
<asp:BoundField DataField="m_h_id" HeaderText="m_h_id" SortExpression="m_h_id" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceAutos" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [m_id], [m_name], [m_h_id] FROM [marke]" FilterExpression="m_name LIKE '%{0}%'" ConflictDetection="CompareAllValues" DeleteCommand="DELETE FROM [marke] WHERE [m_id] = #original_m_id AND [m_name] = #original_m_name AND [m_h_id] = #original_m_h_id" InsertCommand="INSERT INTO [marke] ([m_name], [m_h_id]) VALUES (#m_name, #m_h_id)" OldValuesParameterFormatString="original_{0}" UpdateCommand="UPDATE [marke] SET [m_name] = #m_name, [m_h_id] = #m_h_id WHERE [m_id] = #original_m_id AND [m_name] = #original_m_name AND [m_h_id] = #original_m_h_id" >
<DeleteParameters>
<asp:Parameter Name="original_m_id" Type="Int32" />
<asp:Parameter Name="original_m_name" Type="String" />
<asp:Parameter Name="original_m_h_id" Type="Int32" />
</DeleteParameters>
<FilterParameters>
<asp:ControlParameter Name="m_name" ControlID="searchbox" PropertyName="Text" />
</FilterParameters>
<InsertParameters>
<asp:Parameter Name="m_name" Type="String" />
<asp:Parameter Name="m_h_id" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="m_name" Type="String" />
<asp:Parameter Name="m_h_id" Type="Int32" />
<asp:Parameter Name="original_m_id" Type="Int32" />
<asp:Parameter Name="original_m_name" Type="String" />
<asp:Parameter Name="original_m_h_id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
public partial class Archiv : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
GridView1.DataBind();
}
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> markensuchen(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select m_name from marke where " +
"m_name like #searchbox + '%'";
cmd.Parameters.AddWithValue("#searchbox", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> marken = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
marken.Add(sdr["m_name"].ToString());
}
}
conn.Close();
return marken;
}
}
}
private string SearchString = "";
public string HighlightText(string InputTxt)
{
string Search_Str = searchbox.Text;
// Setup the regular expression and add the Or operator.
Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
// Highlight keywords by calling the
//delegate each time a keyword is found.
return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
}
public string ReplaceKeyWords(Match m)
{
return ("<span class=highlight>" + m.Value + "</span>");
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SearchString = searchbox.Text;
}
protected void btnClear_Click(object sender, EventArgs e)
{
searchbox.Text = "";
SearchString = "";
GridView1.DataBind();
}
}
}
The Title sounds wierd but thats what is actually happening.
I found people with similar problems but there was no answer on these pages.
I have a DetailsView Control which is bound to a ObjectDataSource
Code:
<asp:DetailsView ID="DetailsView1" runat="server" BackColor="#7B7C95" BorderColor="White" BorderWidth="1px" CellPadding="2" ForeColor="White" GridLines="None" Style="height: 80%; width: 80%" AutoGenerateRows="False" DataSourceID="UserTableObjectDataSource" Font-Bold="True" Font-Names="Tahoma" AutoGenerateEditButton="True" OnItemUpdating="DetailsView1_ItemUpdating">
<AlternatingRowStyle BackColor="#393847" />
<FieldHeaderStyle VerticalAlign="Middle" />
<Fields>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<div style="width: 50%; height: auto; overflow: auto;">
<asp:Image ID="Image1" runat="server" AlternateText="No Image Added" ImageUrl='<%# Eval("ImageUrl") %>' />
</div>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" ReadOnly="True" />
<asp:BoundField DataField="PackagesBooked" HeaderText="Packages Booked" SortExpression="PackagesBooked" ReadOnly="True">
<ItemStyle Font-Underline="True" />
</asp:BoundField>
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:BoundField DataField="PhoneNumber" HeaderText="PhoneNumber" SortExpression="PhoneNumber" />
</Fields>
<FooterStyle BackColor="Tan" VerticalAlign="Middle" />
<HeaderStyle BackColor="Tan" Font-Bold="True" VerticalAlign="Middle" />
<PagerStyle BackColor="Silver" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
</asp:DetailsView>
<asp:ObjectDataSource ID="UserTableObjectDataSource" runat="server" SelectMethod="getUser" TypeName="HolidaysForYou.DAL.DbHandler" UpdateMethod="updateUser" ValidateRequestMode="Enabled">
<SelectParameters>
<asp:SessionParameter Name="username" SessionField="Username" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="PhoneNumber" Type="String" />
<asp:SessionParameter Name="username" SessionField="Username" Type="String" />
</UpdateParameters>
</asp:ObjectDataSource>
the update method looks like this
public static void updateUser(string Email, string PhoneNumber, string username)
{
string usernameLower = username.ToLower();
string queryString = "Update [UserTable] SET Email='" + Email + "',PhoneNumber='" + PhoneNumber + "' WHERE ([Name] = '" + usernameLower + "')";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
command.BeginExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
}
When i run the program in debug mode and go slowly step by step, the program works perfectly if i just run it there is no change in the Db.
i also tried calling the updateUser function from the DetailsView1_ItemUpdating function like :
protected void DetailsView1_ItemUpdating(object sender, System.Web.UI.WebControls.DetailsViewUpdateEventArgs e)
{
try
{
string newEmail = (string)e.NewValues["Email"];
string newPhoneNumber = (string)e.NewValues["PhoneNumber"];
if (!UserHomeValidate.userUpdateValidate(newEmail, newPhoneNumber))
{
e.Cancel = true;
Error.Visible = true;
}
else
UserHomeValidate._updateUser(newEmail, newPhoneNumber, Session["Username"].ToString().ToUpper());
}
catch (Exception exception)
{
Utility.LogFile.CreateLogFile(exception);
}
}
where _updateUser is exactly the same as updateUser and still the dataBase is not changed.... this might have something to do with postback but i dont know how that works..
This is getting frustrating a lil help would be appreciated..
Solved the issue...
just had to add
if (!Page.IsPostBack)
DetailsView1.DataBind();
to the page_Load to avoid binding at the postback as then the old values will be passed...
I have used a gridview and linqdatasourse , the gridview will be fill by a linq-stored procedure after clicking a search button.
I did it like below but my grid view is empty.
It seems LinqDataSource2_Selecting does not work.
Please help what is the problem?
public void LinqDataSource2_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
_DataContext = new EDMSDataContext();
var subjectFilter = e.WhereParameters["Subject"];
var query = _DataContext.spQuickSearchDoc(subjectFilter);
e.Result = query;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
this.LinqDataSource2.WhereParameters["Subject"].DefaultValue = this.txtSearchKeywords.Text;
GridViewDocuments.Visible = false;
GridViewDocuments_Search.Visible = true;
this.GridViewDocuments_Search.DataBind();
}
Stored procedure:
ALTER PROCEDURE [dbo].[spQuickSearchDoc]
#Searchtext varchar(50)=null
AS
select DocId,DocumentNo,Title,Unit
from tblDocuments
where DocumentNo like '%'+#SearchText + '%'
or Title like '%'+#SearchText + '%'
or Unit like '%'+#SearchText + '%'
Gridview:
<asp:GridView ID="GridViewDocuments_Search" runat="server" AutoGenerateColumns=False Visible="False" onrowcommand="GridViewDocuments_Search_RowCommand"
DataKeyNames="DocID" PageSize="100" >
<Columns>
<asp:TemplateField HeaderText = "Details">
<ItemTemplate>
<asp:Button ID ="btn_Show" Text="Details" runat= "server" CommandName= "Details" CommandArgument='<%#
Container.DataItemIndex%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DocumentNo" HeaderText="DocumentNo" SortExpression="DocumentNo" />
<asp:BoundField DataField="title" HeaderText="Title" SortExpression="title" />
<asp:BoundField DataField="Docid" HeaderText="Docid" Visible="false" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource2" runat="server"
ContextTypeName="EDMSDataContext" OnSelecting="LinqDataSource2_Selecting">
<WhereParameters>
<asp:ControlParameter Name="Subject"
ControlID="txtSearchKeywords"
PropertyName="Text"
Type="String" />
</WhereParameters>
</asp:LinqDataSource>
You need to add DataSourceID to the GridView, as in:
<asp:GridView ID="GridViewDocuments_Search" runat="server"
. . DataSourceID="LinqDataSource2">
Since it's not set, the GridView is being bound to NULL.
I have a gridview that is filled correctly from 3 tables.
When I update it, it will only update one field (Kommentar) but only the first time.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID,Erledigt,Kommentar"
DataSourceID="ArtikelDataSource">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name"
ReadOnly="True" >
<ControlStyle Width="150px" />
</asp:BoundField>
<asp:BoundField DataField="Beschreibung" HeaderText="Beschreibung"
SortExpression="Beschreibung" ReadOnly="True" >
<ControlStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="Datum" HeaderText="Datum" SortExpression="Datum"
ReadOnly="True" >
<ControlStyle Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="Erledigt" HeaderText="Erledigt"
SortExpression="Erledigt" >
<ControlStyle Width="50px" />
</asp:BoundField>
<asp:BoundField DataField="Kommentar" HeaderText="Kommentar"
SortExpression="Kommentar" >
<ControlStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="LastUpdate" HeaderText="LastUpdate"
SortExpression="LastUpdate" ReadOnly="True" />
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" Visible="False" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="ArtikelDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT ci.Name, ci.Beschreibung, ca.ChkItemID, ca.ChkUserID, ca.Datum, ca.Erledigt, ca.Kommentar, ca.LastUpdate, ca.ID FROM ChecklistActions AS ca INNER JOIN ChecklistItems AS ci ON ca.ChkItemID = ci.ID INNER JOIN ChecklistUsers AS cu ON ca.ChkUserID = cu.ID WHERE (ca.Datum = #datum) AND (cu.Login = #userlogin)"
UpdateCommand="UPDATE ChecklistActions SET Kommentar = #Kommentar, LastUpdate = GETDATE() WHERE (ID = #ID)"
OnSelecting="_data_Selecting"
>
<SelectParameters>
<asp:Parameter Name="userlogin"/>
<asp:Parameter Name="datum"/>
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Kommentar" Type="string"/>
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource>
I have first an empty field "Kommentar", then it is filled, but when I try to change the value again, only the GETDATE() changes value, the content of Kommentar is the same as before.
When I try to change the value of "Erledigt" via SQL
UpdateCommand="UPDATE ChecklistActions SET Erledigt = #Erledigt, Kommentar = #Kommentar, LastUpdate = GETDATE() WHERE (ID = #ID)"
...
<asp:Parameter Name="Erledigt" Type="Int32"/>
nothing (except the Getdate()) is updated at all - not even the field Kommentar at the fist time
It seems that the gridview is sending the old values to the update command (only the first update will receive the new Kommentar-value) which is really irritating ?
you missed , in your UpdateCommand
UPDATE ChecklistActions SET Erledigt = #Erledigt, Kommentar = #Kommentar, LastUpdate = GETDATE() WHERE (ID = #ID)"
edit
Set only the primary key column names on your database tables as DataKeyNames, in this case you only update ChecklistActions table. so set primary key of ChecklistActions as DataKeyNames
Sorry for the convoluted title, but that is the best way I could think to phrase it.
Basically, I have a column of data that is a URL (lets call it URL-A), and another that is hidden which is also a URL(URL-B). I have a function called ConvertURL(string URLin) in the codebehind that will take URL-A and turn it into URL-B.
So in this gridview, if someone were to edit an entry using the native gridview/datasource functionality and change URL-A, how do I get it to run this new URL-A through ConvertURL() and update the URL-B field?
Here is a simple representation of the code (not the actual code):
Code-behind function:
public string ConvertURL(string URLin)
{
Int32 iLocation = URLin.IndexOf("WWW.XYZ.COM");
if (iLocation >= 0)
{
string checkurl = URLin.Replace("WWW.XYZ.COM", "STAGING.XYZ.COM");
return checkurl;
}
else
{
return URLin;
}
}
Data-Source:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:My_AppConnectionString %>"
SelectCommand="SELECT [URL_A], [URL_B], [URLName] FROM [My_App] WHERE ([IsActive] = #IsActive)"
OldValuesParameterFormatString="original_{0}"
UpdateCommand="UPDATE [My_App] SET [URL_A] = #URL_A, [URL_B] = #URL_B, [URLName] = #URLName, [IsActive] = #IsActive WHERE [ID] = #original_ID">
<SelectParameters>
<asp:Parameter DefaultValue="True" Name="IsActive" Type="Boolean" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="URL_A" Type="String" />
<asp:Parameter Name="URL_B" Type="String" />
<asp:Parameter Name="URLName" Type="String" />
<asp:Parameter Name="IsActive" Type="boolean" />
<asp:Parameter Name="original_ID" Type="Int32" />
<asp:Parameter Name="original_URL_A" Type="String" />
<asp:Parameter Name="original_URL_B" Type="String" />
<asp:Parameter Name="original_URLName" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
And Lastly the GridView:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
onrowediting="GridView1_RowEditing"
AutoGenerateColumns="False" CellPadding="3" DataKeyNames="ID"
DataSourceID="SqlDataSource1" EnableModelValidation="False" ForeColor="Black"
GridLines="Vertical" AllowSorting="True" BackColor="White"
BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
AutoGenerateEditButton="True" CausesValidation="false">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" Visible="False" />
<asp:BoundField DataField="URL_A" HeaderText="URL A"
SortExpression="URL_A" />
<asp:BoundField DataField="URL_B" HeaderText="URL B"
SortExpression="URL_B" **Visible="False"** />
<asp:BoundField DataField="URLName" HeaderText="URL Name"
SortExpression="URLName" />
<asp:CheckBoxField DataField="IsActive" HeaderText="Active"
SortExpression="IsActive" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
</asp:GridView>
So to summarize: A user will see a gridview with 3 fields to edit, one of which is URL_A (URL_B is hidden). When they hit edit and update the URL_A field I want to run URL_A through the ConvertURL() function and use that output as the data for URL_B when the update is performed.
I appreciate the help in advance!
Use the RowUpdating event of the grid view and change the new value for URL_B. In that event you will have access to the old values of the row as well as the new values. You can change the new values before they are sent to the data source for the actual update.
Add the event handler to the grid view in the ASPX:
<asp:GridView ID="GridView1" runat="server"
...
OnRowUpdating="GridView1_RowUpdating">
And in the code file handle the event:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Find the current value for URL_A
string urlA = (string)e.NewValues["URL_A"];
// Get the corresponding value for URL_B from the method
string urlB = ConvertURL(urlA);
// Set the new value for the URL_B column before it's sent to the SqlDataSource
e.NewValues["URL_B"] = urlB;
}