I've created a DetailsView that displays data based on a selected item from a GridView. When the DetailsView is under Edit Mode, it displays dropdownlists that contain data from a SQL databind. The data displays in the dropdownlist without issue, but fails to update. All other fields succeed.
The data is bound to the drop down via OnDataBound.
The idea is to populate the SelectedValue with the current data, and populate what it can be changed to. This works without issue. It simply fails to update.
I believe it has to do with syncing the control with the "an" parameter, but am at a loss at how to do so.
Front End Code pertaining to the issue:
<asp:DetailsView ID="userDetails" runat="server"
Height="50px"
Width="400px"
AutoGenerateRows="False"
CellPadding="4"
DataKeyNames="id"
DataSourceID="detailsSqlDataSource"
ForeColor="#333333"
GridLines="None"
OnDataBound="userDetails_ItemEdit">
<AlternatingRowStyle BackColor="White" />
<CommandRowStyle BackColor="#D1DDF1" Font-Bold="True" />
<EditRowStyle BackColor="#2461BF" />
<FieldHeaderStyle BackColor="#DEE8F5" Font-Bold="True" width="125px"/>
<Fields>
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="first_name" HeaderText="First Name" SortExpression="first_name" />
<asp:BoundField DataField="last_name" HeaderText="Last Name" SortExpression="last_name" />
<asp:BoundField DataField="user_name" HeaderText="User Name" SortExpression="user_name" />
<asp:TemplateField HeaderText="T" SortExpression="t">
<EditItemTemplate>
<asp:DropDownList ID="tEditDD" runat="server" SelectedValue='<%# Bind("t") %>'>
<asp:ListItem Value="t1" Text="t1"></asp:ListItem>
<asp:ListItem Value="t2" Text="t2"></asp:ListItem>
<asp:ListItem Value="t3" Text="t3"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("t") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("t") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="P" SortExpression="p">
<EditItemTemplate>
<asp:DropDownList ID="pEditDD" runat="server" SelectedValue='<%# Bind("p") %>'>
<asp:ListItem Value="As" Text="As"></asp:ListItem>
<asp:ListItem Value="An" Text="An"></asp:ListItem>
<asp:ListItem Value="Su" Text="Su"></asp:ListItem>
<asp:ListItem Value="Ad" Text="Ad"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("p") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("p") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="An" SortExpression="an">
<EditItemTemplate>
<asp:DropDownList ID="anEditDD" runat="server">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("an") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("an") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Su" SortExpression="su">
<EditItemTemplate>
<asp:DropDownList ID="suEditDD" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("su") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("su") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="email" HeaderText="E-Mail" SortExpression="email" />
<asp:TemplateField HeaderText="AL" SortExpression="al">
<EditItemTemplate>
<asp:DropDownList ID="alEditDD" runat="server" SelectedValue='<%# Bind("al") %>'>
<asp:ListItem Value="As" Text="As"></asp:ListItem>
<asp:ListItem Value="An" Text="An"></asp:ListItem>
<asp:ListItem Value="Su" Text="Su"></asp:ListItem>
<asp:ListItem Value="Ad" Text="Ad"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="alInsertDD" runat="server" SelectedValue='<%# Bind("al") %>'>
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="As" Text="As"></asp:ListItem>
<asp:ListItem Value="An" Text="An"></asp:ListItem>
<asp:ListItem Value="Su" Text="Su"></asp:ListItem>
<asp:ListItem Value="Ad" Text="Ad"></asp:ListItem>
</asp:DropDownList>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("al") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" />
</Fields>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
</asp:DetailsView>
<asp:SqlDataSource ID="detailsSqlDataSource" runat="server"
ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:CPConnectionString %>"
UpdateCommand="UPDATE [users] SET [first_name] = #first_name, [last_name] = #last_name, [user_name] = #user_name, [t] = #t, [p] = #p, [an] = #an, [su] = #su, [email] = #email, [al] = #al WHERE [id] = #original_id">
<SelectParameters>
<asp:ControlParameter ControlID="usersGrid" Name="id" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="first_name" Type="String" />
<asp:Parameter Name="last_name" Type="String" />
<asp:Parameter Name="user_name" Type="String" />
<asp:Parameter Name="t" Type="String" />
<asp:Parameter Name="p" Type="String" />
<asp:Parameter Name="an" Type="String" />
<asp:Parameter Name="su" Type="String" />
<asp:Parameter Name="email" Type="String" />
<asp:Parameter Name="al" Type="String" />
<asp:Parameter Name="original_id" Type="Int32" />
<asp:Parameter Name="original_first_name" Type="String" />
<asp:Parameter Name="original_last_name" Type="String" />
<asp:Parameter Name="original_user_name" Type="String" />
<asp:Parameter Name="original_t" Type="String" />
<asp:Parameter Name="original_p" Type="String" />
<asp:Parameter Name="original_an" Type="String" />
<asp:Parameter Name="original_su" Type="String" />
<asp:Parameter Name="original_email" Type="String" />
<asp:Parameter Name="original_al" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
Code Behind:
protected void userDetails_ItemEdit(object sender, EventArgs e)
{
if (userDetails.CurrentMode == DetailsViewMode.Edit)
{
AnDD();
}
}
protected void AnDD()
{
DropDownList anEditDD = userDetails.FindControl("anEditDD") as DropDownList;
string userName = ((TextBox)userDetails.Rows[3].Cells[1].Controls[0]).Text;
string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["CPConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
con.Open();
string currentAnSqlSelect = "SELECT an FROM users WHERE user_name='" + userName + "'";
SqlDataReader currentReader;
SqlCommand ccmd = new SqlCommand(currentAnSqlSelect, con);
currentReader = ccmd.ExecuteReader();
while (currentReader.Read())
{
ListItem currentList = new ListItem();
currentList.Text = currentReader["an"].ToString();
errorLBL.Text = currentReader["an"].ToString();
anEditDD.Items.Add(currentList);
}
currentReader.Close();
string anSqlSelect = "SELECT first_name, last_name FROM users WHERE position='An'";
SqlDataReader anReader;
SqlCommand cmd = new SqlCommand(anSqlSelect, con);
anReader = cmd.ExecuteReader();
while (anReader.Read())
{
ListItem anList = new ListItem();
anList.Text = anReader["first_name"].ToString() + " " + anReader["last_name"].ToString();
anEditDD.Items.Add(anList);
}
anReader.Close();
con.Close();
anEditDD.Items.Add("N/A");
anEditDD.DataBind();
anEditDD.SelectedIndex = 0;
}
Your update command appears to be part of the details view, and not part of any ObjectDataSource. Can you confirm your markup above is correct?
Edit
In your UpdateParameters group, you aren't getting the values from the controls. Try doing the following:
<UpdateParameters>
<asp:Parameter />
...snip
<asp:ControlParameter Name="an" ControlID="idOfWhateverControlHasTheUserSetValue" Type="String" />
...snip
</UpdateParameters>
I took your advice and did a little research about using the ControlParameter.
The fix was adding the following to the Update Parameters, and removing the auto-populated parameters for 'an'. Thanks for the help, Nick.
<asp:ControlParameter Name="an" ControlID="userDetails$anEditDD" PropertyName="SelectedValue" Type="String" />
Related
I am a newbie and I have recently started working developing a web application, I do not have much experience so if you are able to solve the problem and explain it in detail I would be much more than grateful. I am trying to insert in Visual Studio through a Gridview a series of data in my database. For this I have several textboxes and a dropdownlist in the FooterRow to obtain a series of data and the other data that is missing in the insert I obtain it by looking at other GridViews/querying the database. At the end, after successfully obtaining all the data I need to insert through the SqlDataSource, I am ready to insert the data with cmd.ExecuteNonQuery(); But when trying to do it I got this error: System.Data.SqlClient.SqlException: 'You must declare the scalar variable '#EXPEDIENTE'.'
My GridView code is :
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource3" ForeColor="#333333" GridLines="None" Width="723px" ShowFooter="True" AllowPaging="True" AllowSorting="True" DataKeyNames="EXPEDIENTE,NUMERO_COMENTARIO" OnSelectedIndexChanged="GridView3_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
<asp:TemplateField HeaderText="EXPEDIENTE" SortExpression="EXPEDIENTE">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("EXPEDIENTE") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("EXPEDIENTE") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" OnClick="Click_addUser" >Añadir Comentario</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NUMERO_COMENTARIO" SortExpression="NUMERO_COMENTARIO">
<EditItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("NUMERO_COMENTARIO") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("NUMERO_COMENTARIO") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FECHA" SortExpression="FECHA">
<EditItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("FECHA") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("FECHA") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="FECHA" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="COMENTARIO" SortExpression="COMENTARIO">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("COMENTARIO") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("COMENTARIO") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="COMENTARIO" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="USUARIO" SortExpression="USUARIO">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("USUARIO") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("USUARIO") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="false" DataSourceID="SqlDataSource4" DataTextField="NOMBRE_USUARIO"
DataValueField="NOMBRE_USUARIO" AppendDataBoundItems="True" ></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:DESAConnectionString %>"
SelectCommand="SELECT A.ID_EXPE EXPEDIENTE,A.ID_COEX NUMERO_COMENTARIO, convert(varchar, A.FECHA_COMENTARIO, 3 ) FECHA, A.COMENTARIO,E.NOMBRE_USUARIO USUARIO FROM COEX_COMENTARIOS_EXPEDIENTES A , EXPE_EXPEDIENTES B,CLIE_CLIENTES C,EXCL_EXPEDIENTES_CLIENTES D,USUA_USUARIOS E WHERE A.ID_EXPE = B.ID_EXPE AND B.ID_EXPE=D.ID_EXPE AND C.ID_CLIENTE=D.ID_CLIENTE AND E.ID_USUA=A.ID_USUA;"
DeleteCommand="DELETE FROM [COEX_COMENTARIOS_EXPEDIENTES] WHERE ([ID_EXPE] = #EXPEDIENTE) AND ([ID_COEX] = #NUMERO_COMENTARIO)"
InsertCommand="INSERT INTO [COEX_COMENTARIOS_EXPEDIENTES] ([ID_EXPE], [ID_COEX], [FECHA_COMENTARIO], [COMENTARIO], [ID_USUA]) VALUES (#EXPEDIENTE,#NUMERO_COMENTARIO,#FECHA,COMENTARIO,#USUARIO)"
UpdateCommand="UPDATE [COEX_COMENTARIOS_EXPEDIENTES] SET [COMENTARIO] = #COMENTARIO, [ID_USUA] =(SELECT ID_USUA FROM USUA_USUARIOS WHERE NOMBRE_USUARIO=#USUARIO) WHERE [ID_EXPE] = #EXPEDIENTE AND [ID_COEX] = #NUMERO_COMENTARIO">
<DeleteParameters>
<asp:Parameter Name="ID_EXPE" Type="Int32" />
<asp:Parameter Name="ID_COEX" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="ID_EXPE" Type="Int32" />
<asp:Parameter Name="ID_COEX" Type="Int32" />
<asp:Parameter DbType="Date" Name="FECHA_COMENTARIO" />
<asp:Parameter Name="COMENTARIO" Type="String" />
<asp:Parameter Name="ID_USUA" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter DbType="Date" Name="FECHA_COMENTARIO" />
<asp:Parameter Name="COMENTARIO" Type="String" />
<asp:Parameter Name="ID_USUA" Type="Int32" />
<asp:Parameter Name="ID_EXPE" Type="Int32" />
<asp:Parameter Name="ID_COEX" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
And the Code of the process that gets executed when i click on the "Añadir comentario" (Add comment in spanish) button is :
protected void Click_addUser(object sender, EventArgs e)
{
bool conected = false;
try
{
conection.Close();
conection.Open();
conected = true;
}
catch (SqlException ex)
{
string errorconection = ex.Message;
}
GridViewRow gvr = (GridViewRow)GridView3.FooterRow;
DropDownList ddl = (DropDownList)gvr.FindControl("DropDownList1");
// String nombre_usua = ((DropDownList)GridView3.FooterRow.FindControl("USUARIO")).Text;
String nombre_usua=ddl.SelectedValue;
String id_usua;
String sSql = "select ID_USUA FROM USUA_USUARIOS WHERE NOMBRE_USUARIO='" + nombre_usua + "'";
SqlDataSource5.SelectCommand = sSql;
DataView dv = (DataView)SqlDataSource5.Select(DataSourceSelectArguments.Empty);
id_usua=dv.Table.Rows[0][0].ToString();
sSql = "select ID_EXPE FROM EXPE_EXPEDIENTES WHERE ID_EXPE="+GridView2.Rows[1].Cells[0].Text+"";
SqlDataSource6.SelectCommand = sSql;
dv = (DataView)SqlDataSource6.Select(DataSourceSelectArguments.Empty);
string id_Expe=dv.Table.Rows[0][0].ToString();
sSql = "select MAX(ID_COEX)+1 from COEX_COMENTARIOS_EXPEDIENTES where ID_EXPE="+id_Expe+"";
SqlDataSource7.SelectCommand = sSql;
dv = (DataView)SqlDataSource7.Select(DataSourceSelectArguments.Empty);
string id_Coex = dv.Table.Rows[0][0].ToString();
SqlCommand cmd = new SqlCommand("INSERT INTO [COEX_COMENTARIOS_EXPEDIENTES] ([ID_EXPE], [ID_COEX], [FECHA_COMENTARIO], [COMENTARIO], [ID_USUA]) VALUES (#EXPEDIENTE, #NUMERO_COMENTARIO, #FECHA, #COMENTARIO,#USUARIO)", conection);
SqlParameter param = new SqlParameter();
param.ParameterName = "#EXPEDIENTE";
param.Value = id_Expe;
cmd.Parameters.Add(param);
SqlParameter param2 = new SqlParameter();
param.ParameterName = "#NUMERO_COMENTARIO";
param.Value = id_Coex;
cmd.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter();
param.ParameterName = "#FECHA";
param.Value = ((TextBox)GridView3.FooterRow.FindControl("FECHA")).Text;
cmd.Parameters.Add(param3);
SqlParameter param4 = new SqlParameter();
param.ParameterName = "#COMENTARIO";
param.Value = ((TextBox)GridView3.FooterRow.FindControl("COMENTARIO")).Text; ;
cmd.Parameters.Add(param4);
SqlParameter param5 = new SqlParameter();
param.ParameterName = "#USUARIO";
param.Value = id_usua;
cmd.Parameters.Add(param5);
cmd.ExecuteNonQuery();}
The error is on the cmd.ExecuteNonQuery();
I am turning crazy trying to find a solution , if anyone could help me i would be so thankful.Thank you very much in advance
i already found the problem. In the C# code i used the parameter param all the time and i needed to use param2 , param3, param4 etc.... Changed that and everything works perfect.
I have a page with a details view and a grid view (each with their own data source. I can't figure out why the update says it's successful but don't update the table. the details view works fine. The grid view is only suppose to show data related to what's in the details view. If I hard code the values in the source it works but when I change it back it blows up. here's my code
<asp:SqlDataSource OnUpdated="dsCar_Updated" ID="dsCar" runat="server"
ConnectionString="<%$ ConnectionStrings:VehicalList %>"
ProviderName="<%$ ConnectionStrings:VehicalList.ProviderName %>"
SelectCommand="SELECT Car.* FROM Car WHERE (VIN = ?)"
UpdateCommand="UPDATE Car SET [Branch ID] = ?, [State Registration] = ?, [License Plate] = ?, Color = ?, Model = ?, [Car Year] = ?, [Plate Expiration] = ? WHERE (VIN = ?)">
<SelectParameters>
<asp:QueryStringParameter Name="?" QueryStringField="VIN" />
</SelectParameters>
</asp:SqlDataSource>
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
DataSourceID="dsCar" Height="50px" Width="265px" CellPadding="4"
ForeColor="#333333" GridLines="None" DataKeyNames="VIN" DefaultMode="Edit">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
<EditRowStyle BackColor="#999999" />
<FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
<Fields>
<asp:BoundField DataField="VIN" HeaderText="VIN" ReadOnly="True"
SortExpression="VIN" />
<asp:TemplateField HeaderText="Branch Name" SortExpression="Branch ID">
<EditItemTemplate>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:VehicalList %>"
ProviderName="<%$ ConnectionStrings:VehicalList.ProviderName %>"
SelectCommand="SELECT * FROM [Branch]"></asp:SqlDataSource>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource2" DataTextField="Branch Name"
DataValueField="Branch ID" SelectedValue='<%# Bind("[Branch ID]") %>'>
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:VehicalList %>"
ProviderName="<%$ ConnectionStrings:VehicalList.ProviderName %>"
SelectCommand="SELECT * FROM [Branch]"></asp:SqlDataSource>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource3" DataTextField="Branch Name"
DataValueField="Branch ID" SelectedValue='<%# Bind("[Branch ID]") %>'>
</asp:DropDownList>
</InsertItemTemplate>
<ItemTemplate>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:VehicalList %>"
ProviderName="<%$ ConnectionStrings:VehicalList.ProviderName %>"
SelectCommand="SELECT * FROM [Branch]"></asp:SqlDataSource>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Branch Name"
DataValueField="Branch ID" Enabled="False" SelectedValue='<%# Bind("[Branch ID]") %>'>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="State Registration" HeaderText="State Registration"
SortExpression="State Registration" />
<asp:BoundField DataField="License Plate" HeaderText="License Plate"
SortExpression="License Plate" />
<asp:BoundField DataField="Color" HeaderText="Color" SortExpression="Color" />
<asp:TemplateField HeaderText="Model" SortExpression="Model">
<EditItemTemplate>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:VehicalList %>"
ProviderName="<%$ ConnectionStrings:VehicalList.ProviderName %>"
SelectCommand="SELECT * FROM [Model]"></asp:SqlDataSource>
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="SqlDataSource4" DataTextField="Model Name"
DataValueField="ModelID" SelectedValue='<%# Bind("Model") %>'>
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Model") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:VehicalList %>"
ProviderName="<%$ ConnectionStrings:VehicalList.ProviderName %>"
SelectCommand="SELECT * FROM [Model]"></asp:SqlDataSource>
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="SqlDataSource4" DataTextField="Model Name"
DataValueField="ModelID" SelectedValue='<%# Bind("Model") %>'
Enabled="False">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Car Year" HeaderText="Car Year"
SortExpression="Car Year" />
<asp:TemplateField HeaderText="Plate Expiration"
SortExpression="Plate Expiration">
<EditItemTemplate>
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:VehicalList %>"
ProviderName="<%$ ConnectionStrings:VehicalList.ProviderName %>"
SelectCommand="SELECT * FROM [Car]"></asp:SqlDataSource>
<asp:Calendar ID="Calendar1" runat="server"
onselectionchanged="Calendar1_SelectionChanged"
VisibleDate='<%# Eval("[Plate Expiration]") %>'
SelectedDate='<%# Bind("[Plate Expiration]") %>'></asp:Calendar>
<asp:TextBox ID="txtDateEdit" runat="server"
Text='<%# Bind("[Plate Expiration]") %>'></asp:TextBox>
<br />
</EditItemTemplate>
<InsertItemTemplate>
<asp:Calendar ID="Calendar1" runat="server"
onselectionchanged="Calendar1_SelectionChanged"
VisibleDate='<%# Eval("[Plate Expiration]") %>'></asp:Calendar>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("[Plate Expiration]") %>' Visible="false"></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<br />
<asp:Label ID="Label1" runat="server" Text='<%# Eval("[Plate Expiration]") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource OnUpdated="dsMaintance_Updated" ID="dsMaintance" runat="server"
ConnectionString="<%$ ConnectionStrings:VehicalList %>"
DeleteCommand="DELETE FROM [Maintenance] WHERE [MainteanceID] = ?"
InsertCommand="INSERT INTO [Maintenance] ([MainteanceID], [VIN], [Procedure ID], [Date]) VALUES (?, ?, ?, ?)"
ProviderName="<%$ ConnectionStrings:VehicalList.ProviderName %>"
SelectCommand="SELECT MainteanceID, VIN, [Procedure ID], [Date] FROM Maintenance WHERE (VIN = ?)"
UpdateCommand="UPDATE Maintenance SET [Procedure ID] = ?, [Date] = ? WHERE (MainteanceID = ?)">
<DeleteParameters>
<asp:Parameter Name="MainteanceID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="MainteanceID" Type="Int32" />
<asp:Parameter Name="VIN" Type="String" />
<asp:Parameter Name="Procedure_ID" Type="Int32" />
<asp:Parameter Name="Date" Type="DateTime" />
</InsertParameters>
<SelectParameters>
<asp:QueryStringParameter Name="VIN" QueryStringField="VIN" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="MainteanceID" Type="Int32" />
<asp:Parameter Name="VIN" Type="String" />
<asp:Parameter Name="Procedure_ID" Type="Int32" />
<asp:Parameter Name="Date" Type="DateTime" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="MainteanceID" DataSourceID="dsMaintance" BackColor="White"
BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3"
CellSpacing="1" GridLines="None">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="MainteanceID" HeaderText="MainteanceID"
InsertVisible="False" ReadOnly="True" SortExpression="MainteanceID" />
<asp:BoundField DataField="VIN" HeaderText="VIN" SortExpression="VIN" />
<asp:BoundField DataField="Procedure ID" HeaderText="Procedure ID"
SortExpression="Procedure ID" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
</Columns>
</asp:GridView>
You should pass the proper parameters to the UpdateParameters section. It looks like you have a copy-paste problem (maybe you copied the section from the InsertParameters section). Your UPDATE statement needs only 3 parameters.
<asp:SqlDataSource OnUpdated="dsMaintance_Updated" ID="dsMaintance" runat="server"
ConnectionString="<%$ ConnectionStrings:VehicalList %>"
DeleteCommand="DELETE FROM [Maintenance] WHERE [MainteanceID] = ?"
InsertCommand="INSERT INTO [Maintenance] ([MainteanceID], [VIN], [Procedure ID], [Date]) VALUES (?, ?, ?, ?)"
ProviderName="<%$ ConnectionStrings:VehicalList.ProviderName %>"
SelectCommand="SELECT MainteanceID, VIN, [Procedure ID], [Date] FROM Maintenance WHERE (VIN = ?)"
UpdateCommand="UPDATE Maintenance SET [Procedure ID] = ?, [Date] = ? WHERE (MainteanceID = ?)">
<DeleteParameters>
<asp:Parameter Name="MainteanceID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="MainteanceID" Type="Int32" />
<asp:Parameter Name="VIN" Type="String" />
<asp:Parameter Name="Procedure_ID" Type="Int32" />
<asp:Parameter Name="Date" Type="DateTime" />
</InsertParameters>
<SelectParameters>
<asp:QueryStringParameter Name="VIN" QueryStringField="VIN" Type="String" />
</SelectParameters>
<UpdateParameters>
<%--<asp:Parameter Name="MainteanceID" Type="Int32" />--%>
<%--<asp:Parameter Name="VIN" Type="String" />--%>
<asp:Parameter Name="Procedure_ID" Type="Int32" />
<asp:Parameter Name="Date" Type="DateTime" />
</UpdateParameters>
</asp:SqlDataSource>
I have a RadGrid with a Checkbox inside an EditItemTemplate for an Active or Inactive status.
This checkbox only shows when the item is being updated or added as new. I have a ControlParameter for the checkbox, but since it is recursive with many of these checkboxes in the list, it throws the good old "Could not find control 'cbActive' in ControlParameter" Error.
I dont have any real CS code other than the Radgrid binding on page load.
ASPX Code:
<telerik:RadGrid ID="RadGrid1" runat="server" Skin="Vista" Width="500px"
GridLines="None" AllowFilteringByColumn="False" AllowSorting="True" OnExportCellFormatting="RadGrid1_ExportCellFormatting"
AllowAutomaticInserts="True" AllowAutomaticDeletes="true" AllowAutomaticUpdates="True" AutoGenerateEditColumn="True" AutoGenerateDeleteColumn="true">
<MasterTableView AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1" ItemStyle-HorizontalAlign="Left" CommandItemDisplay="TopAndBottom">
<Columns>
<telerik:GridBoundColumn DataField="ID" HeaderText="ID" SortExpression="ID"
UniqueName="ID" Visible="False" ReadOnly="true">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn HeaderText="Active" SortExpression="Active" UniqueName="Active" ItemStyle-Width="100" Visible="false">
<EditItemTemplate>
<asp:CheckBox ID="cbActive" runat="server" Checked='<%# GenerateBindString(Container.DataItem) %>' />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:LBCust %>"
SelectCommand="SELECT * FROM [LBX_Portal_AccountNumbers] WHERE ([Site] = #Site) AND (Active=#Active OR #Active = '0') ORDER BY AccountNumber"
DeleteCommand="DELETE FROM [LBX_Portal_AccountNumbers] WHERE [ID] = #ID"
InsertCommand="INSERT INTO [LBX_Portal_AccountNumbers] ([AccountNumber], [Site], [Active]) VALUES (#AccountNumber, #Site, #Active)"
UpdateCommand="UPDATE [LBX_Portal_AccountNumbers] SET [AccountNumber] = #AccountNumber, [Active] = #Active WHERE [ID] = #ID">
<SelectParameters>
<asp:ControlParameter ControlID="dd_Status" Name="Active"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="AccountNumber" Type="String" />
<asp:Parameter Name="Site" Type="String" />
<asp:ControlParameter ControlID="cbActive"
PropertyName="Checked" Type="Boolean" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="AccountNumber" Type="String" />
<asp:ControlParameter ControlID="cbActive"
PropertyName="Checked" Type="Boolean" />
</UpdateParameters>
</asp:SqlDataSource>
You aren't going to be able to set the value through a control parameter; what you can do though, is use an <asp:Parameter> instead, and set the DefaultValue property on the parameter via:
sqlDataSource1.SelectParameters[0].DefaultValue = "X"
Or, with the Grids, I know with the GridView it has a collection of values that it used to perform the update with; you could add an entry representing the checkbox control, which would get pushed into the data source. I know know if the RadGrid has the same option.
So it took a lot of looking around but i couldnt do this without tapping into the commands via the CS. Here is my new Code for it to work:
<telerik:RadGrid ID="RadGrid1" runat="server" Skin="Vista" Width="500px"
GridLines="None" AllowFilteringByColumn="False" AllowSorting="True" OnExportCellFormatting="RadGrid1_ExportCellFormatting"
AllowAutomaticInserts="True" AllowAutomaticDeletes="true" AllowAutomaticUpdates="True" AutoGenerateEditColumn="True" AutoGenerateDeleteColumn="true" OnItemCommand="RadGrid1_ItemCommand">
<MasterTableView AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1" ItemStyle-HorizontalAlign="Left" CommandItemDisplay="TopAndBottom">
<Columns>
<telerik:GridTemplateColumn HeaderText="ID" SortExpression="ID" UniqueName="ID" Visible="false" ReadOnly="true">
<ItemTemplate>
<asp:Label ID="lblIDView" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="ID" SortExpression="IDEdit" UniqueName="IDEdit" Visible="false">
<ItemTemplate />
<EditItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="AccountNumber" HeaderText="Sapphire Account Number"
SortExpression="AccountNumber" UniqueName="AccountNumberView" ReadOnly="true" ItemStyle-Width="400">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn HeaderText="Account Number" SortExpression="AccountNumber" UniqueName="AccountNumber" Visible="false">
<ItemTemplate />
<EditItemTemplate>
<asp:Textbox ID="txtAccountNumber" runat="server" Text='<%# Bind("AccountNumber") %>' />
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Active" SortExpression="Active" UniqueName="Active" ItemStyle-Width="100" Visible="false">
<ItemTemplate />
<EditItemTemplate>
<asp:CheckBox ID="cbActive" runat="server" Checked='<%# GenerateBindString(Container.DataItem) %>' />
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Status" SortExpression="Active" UniqueName="Active" ItemStyle-Width="100">
<ItemTemplate>
<asp:Label ID="lblActive" runat="server" Text='<%# Convert.ToBoolean(GenerateBindString(Container.DataItem)) == true ? "Active" : "Inactive" %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:LBCust %>"
SelectCommand="SELECT * FROM [LBX_Portal_AccountNumbers] WHERE ([Site] = #Site) AND (Active=#Active OR #Active = '0') ORDER BY AccountNumber"
DeleteCommand="DELETE FROM [LBX_Portal_AccountNumbers] WHERE [ID] = #ID"
InsertCommand="INSERT INTO [LBX_Portal_AccountNumbers] ([AccountNumber], [Site], [Active]) VALUES (#AccountNumber, #Site, #Active)"
UpdateCommand="UPDATE [LBX_Portal_AccountNumbers] SET [AccountNumber] = #AccountNumber, [Active] = #Active WHERE [ID] = #ID">
<SelectParameters>
<asp:ControlParameter ControlID="dd_Status" Name="Active"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="AccountNumber" Type="String" />
<asp:Parameter Name="Site" Type="String" />
<asp:Parameter Name="Active" Type="Boolean" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="AccountNumber" Type="String" />
<asp:Parameter Name="Active" Type="Boolean" />
</UpdateParameters>
</asp:SqlDataSource>
CS CODE:
protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
if (e.CommandName == "PerformInsert")
{
GridEditFormItem gridEditFormItem = (GridEditFormItem)e.Item;
Label lblID = (Label)gridEditFormItem.FindControl("lblID");
TextBox txtAccountNumber = (TextBox)gridEditFormItem.FindControl("txtAccountNumber");
CheckBox cbActive = (CheckBox)gridEditFormItem.FindControl("cbActive");
bool isActive = false;
if (cbActive.Checked)
isActive = true;
else
isActive = false;
string SqlStr = "INSERT INTO [LBX_Portal_AccountNumbers] ([AccountNumber], [Site], [Active])";
SqlStr += " VALUES ('" + txtAccountNumber.Text + "'" + ", '" + SiteName + "'" + ", '" + isActive + "')";
SqlDataSource1.InsertCommand = SqlStr;
SqlDataSource1.Insert();
}
if (e.CommandName == "Update")
{
GridEditFormItem gridEditFormItem = (GridEditFormItem)e.Item;
Label lblID = (Label)gridEditFormItem.FindControl("lblID");
TextBox txtAccountNumber = (TextBox)gridEditFormItem.FindControl("txtAccountNumber");
CheckBox cbActive = (CheckBox)gridEditFormItem.FindControl("cbActive");
bool isActive = false;
if (cbActive.Checked)
isActive = true;
else
isActive = false;
string SqlStr = "UPDATE [LBX_Portal_AccountNumbers] SET [AccountNumber] = '" + txtAccountNumber.Text;
SqlStr += "', [Active] = '" + isActive + "' WHERE [ID] = " + lblID.Text;
SqlDataSource1.UpdateCommand = SqlStr;
SqlDataSource1.Update();
}
}
I was following this so far everything is fine with a textbox but when try to modify it to checkbox it gives an error: Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.Web.UI.WebControls.CheckBox'.
Its working when I use TextBox but how can I make all the CheckBox editable in bulk updates?
Here's the sample code behind
private bool tableCopied = false;
private DataTable originalDataTable;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
if (!tableCopied)
{
originalDataTable = ((DataRowView)e.Row.DataItem).Row.Table.Copy();
ViewState["originalValueTable"] = originalDataTable;
tableCopied = true;
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
originalDataTable = (DataTable)ViewState["originalValueTable"];
foreach (GridViewRow r in GridView1.Rows)
if (IsRowModified(r))
{
GridView1.UpdateRow(r.RowIndex, false);
}
tableCopied = false;
GridView1.DataBind();
}
protected bool IsRowModified(GridViewRow r)
{
int currentID;
string currentreservedate;
string currentisapproved;
currentID = Convert.ToInt32(GridView1.DataKeys[0].Value);
currentreservedate = ((TextBox)r.FindControl("reservedateTextBox")).Text;
currentisapproved = ((CheckBox)r.FindControl("isapprovedCheckBox")).Text;
DataRow row = originalDataTable.Select(String.Format("reservationid = {0}", currentID))[0];
if (!currentreservedate.Equals(row["reservedate"].ToString()))
if (!currentisapproved.Equals(row["isapproved"].ToString()))
{
return true;
}
return false;
}
}
}
Here's the aspx markup
Pending Reservation<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT dbo.BookReservation.reservationid, dbo.BookReservation.bookid, dbo.BookReservation.EmployeeID, dbo.BookReservation.reservedate, dbo.BookReservation.isapproved, dbo.BookReservation.reschedule, dbo.BookReservation.isdeleted, dbo.TblBooks.booktitle FROM dbo.BookReservation INNER JOIN dbo.TblBooks ON dbo.BookReservation.bookid = dbo.TblBooks.bookid"
DeleteCommand="DELETE FROM [BookReservation] WHERE [reservationid] = #reservationid"
InsertCommand="INSERT INTO [BookReservation] ([bookid], [EmployeeID], [reservedate], [isapproved], [reschedule], [isdeleted]) VALUES (#bookid, #EmployeeID, #reservedate, #isapproved, #reschedule, #isdeleted)"
UpdateCommand="UPDATE [BookReservation] SET [bookid] = #bookid, [EmployeeID] = #EmployeeID, [reservedate] = #reservedate, [isapproved] = #isapproved, [reschedule] = #reschedule, [isdeleted] = #isdeleted WHERE [reservationid] = #reservationid">
<DeleteParameters>
<asp:Parameter Name="reservationid" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="bookid" Type="Int64" />
<asp:Parameter Name="EmployeeID" Type="String" />
<asp:Parameter Name="reservedate" Type="DateTime" />
<asp:Parameter Name="isapproved" Type="Boolean" />
<asp:Parameter Name="reschedule" Type="Boolean" />
<asp:Parameter Name="isdeleted" Type="Boolean" />
<asp:Parameter Name="reservationid" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="bookid" Type="Int64" />
<asp:Parameter Name="EmployeeID" Type="String" />
<asp:Parameter Name="reservedate" Type="DateTime" />
<asp:Parameter Name="isapproved" Type="Boolean" />
<asp:Parameter Name="reschedule" Type="Boolean" />
<asp:Parameter Name="isdeleted" Type="Boolean" />
</InsertParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" AllowSorting="true"
DataKeyNames="reservationid, bookid, EmployeeID, reservedate " DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField DataField="reservationid" HeaderText="reservationid"
InsertVisible="False" ReadOnly="True"
SortExpression="reservationid" Visible="False" />
<asp:BoundField DataField="bookid" HeaderText="bookid"
SortExpression="bookid" Visible="False" />
<asp:BoundField DataField="booktitle" HeaderText="Title"
SortExpression="booktitle" />
<asp:BoundField DataField="EmployeeID" HeaderText="Reserved by"
SortExpression="EmployeeID" />
<%--<asp:BoundField DataField="reservedate" HeaderText="Date reserved"
SortExpression="reservedate" />--%>
<asp:TemplateField HeaderText="Reserve Date"
SortExpression="reservedate">
<EditItemTemplate>
<asp:TextBox ID="reservedateTextBox" runat="server" Text='<%# Bind("reservedate") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="reservedateTextBox" runat="server" Text='<%# Bind("reservedate") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:CheckBoxField DataField="isapproved" HeaderText="Approved"
SortExpression="isapproved" />--%>
<asp:TemplateField HeaderText="Apprvoed"
SortExpression="isapproved">
<EditItemTemplate>
<asp:TextBox ID="isapprovedCheckBox" runat="server" Text='<%# Bind("isapproved") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="isapprovedCheckBox" runat="server" Text='<%# Bind("isapproved") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:CheckBoxField DataField="reschedule" HeaderText="Reschedule"
SortExpression="reschedule" />
<asp:CheckBoxField DataField="isdeleted" HeaderText="Deleted"
SortExpression="isdeleted" />
</Columns>
</asp:GridView>
<br />
<br />
<asp:Button ID="UpdateButton" runat="server" Text="Update" OnClick="UpdateButton_Click" />
<br />
Help would be much appreciated! Thanks in advance!
I think that to answer this question, the contents of the aspx file are required, but I'll try to help. More than likely the element in your form, isapprovedCheckBox, is still set to the the tag asp:Text. As a result the system can't convert the textbox to a checkbox.
Could you include your aspx content as well?
I want to put the current date in my formview 'dateadded' but its not showing when I load it in the browser. I'm using code behind but how can I display it with date and time?
Here's a my code behind.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LibrarySystem.AdminPage
{
public partial class ManageBooks : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(FormView1.CurrentMode == FormViewMode.Insert)
{
TextBox dateadded = FormView1.FindControl("dateaddedTextBox") as TextBox;
dateadded.Text = DateTime.Now.ToString("d");
}
}
}
}
Here's my complete design
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Lending.aspx.cs" Inherits="LibrarySystem.Test" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<h3>
Lending of Books</h3>
<p>
<asp:FormView ID="FormView1" runat="server" DataSourceID="lendDataSource" DefaultMode="Insert" OnDataBound="FormView1_DataBound">
<EditItemTemplate>
Book ID/ISBN:
<asp:TextBox ID="bookidTextBox" runat="server" Text='<%# Bind("bookid") %>' />
<br />
Book Title:
<asp:TextBox ID="booktitleTextBox" runat="server"
Text='<%# Bind("booktitle") %>' />
<br />
Employee ID:
<asp:TextBox ID="employeeidTextBox" runat="server"
Text='<%# Bind("employeeid") %>' />
<br />
Department:
<asp:TextBox ID="departmentTextBox" runat="server"
Text='<%# Bind("department") %>' />
<br />
Date borrowed:
<asp:TextBox ID="dateborrowedTextBox" runat="server"
Text='<%# Bind("dateborrowed") %>' />
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<InsertItemTemplate>
Book:
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="booktitleDataSource" DataTextField="booktitle"
DataValueField="bookid" SelectedValue='<%# Bind("bookid", "{0}") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="booktitleDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [bookid], [booktitle] FROM [TblBooks]">
</asp:SqlDataSource>
<br />
Employee ID:
<asp:TextBox ID="employeeidTextBox" runat="server"
Text='<%# Bind("employeeid") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="* Required" ControlToValidate="employeeidTextBox" ValidationGroup="lendbook">
</asp:RequiredFieldValidator>
<br />
Department:
<asp:TextBox ID="departmentTextBox" runat="server"
Text='<%# Bind("department") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="* Required" ControlToValidate="departmentTextBox" ValidationGroup="lendbook">
</asp:RequiredFieldValidator>
<br />
Date borrowed:
<asp:TextBox ID="dateborrowedTextBox" runat="server"
Text='<%# Bind("dateborrowed") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="* Required" ControlToValidate="dateborrowedTextBox" ValidationGroup="lendbook">
</asp:RequiredFieldValidator>
<br />
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" ValidationGroup="lendbook"
CommandName="Insert" Text="Insert" />
<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</ItemTemplate>
<EmptyDataTemplate>
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</EmptyDataTemplate>
</asp:FormView>
</p>
<p>
<asp:SqlDataSource ID="lendDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
DeleteCommand="DELETE FROM [LendTable] WHERE [lenid] = #lenid"
InsertCommand="INSERT INTO [LendTable] ([bookid], [employeeid], [department], [dateborrowed], [datereturned]) VALUES (#bookid, #employeeid, #department, #dateborrowed, #datereturned)"
SelectCommand="SELECT dbo.LendTable.bookid, dbo.TblBooks.booktitle, dbo.LendTable.employeeid, dbo.LendTable.department, dbo.LendTable.dateborrowed FROM dbo.LendTable INNER JOIN dbo.TblBooks ON dbo.LendTable.bookid = dbo.TblBooks.bookid"
UpdateCommand="UPDATE [LendTable] SET [bookid] = #bookid, [employeeid] = #employeeid, [department] = #department, [dateborrowed] = #dateborrowed, [datereturned] = #datereturned WHERE [lenid] = #lenid">
<DeleteParameters>
<asp:Parameter Name="lenid" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="bookid" Type="Int64" />
<asp:Parameter Name="employeeid" Type="string" />
<asp:Parameter Name="department" Type="String" />
<asp:Parameter Name="dateborrowed" Type="DateTime" />
<asp:Parameter Name="datereturned" Type="DateTime" />
<asp:Parameter Name="lenid" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="bookid" Type="Int64" />
<asp:Parameter Name="employeeid" Type="string" />
<asp:Parameter Name="department" Type="String" />
<asp:Parameter Name="dateborrowed" Type="DateTime" />
<asp:Parameter Name="datereturned" Type="DateTime" />
</InsertParameters>
</asp:SqlDataSource>
</p>
<p>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" CellPadding="4"
DataKeyNames="lenid" DataSourceID="lendgridviewDataSource" ForeColor="#333333"
GridLines="None">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="bookid" HeaderText="Book ID/ISBN"
SortExpression="bookid" />
<asp:BoundField DataField="booktitle" HeaderText="Book Title"
SortExpression="booktitle" />
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"
SortExpression="EmployeeID" />
<asp:BoundField DataField="department" HeaderText="Department"
SortExpression="department" />
<asp:BoundField DataField="dateborrowed" HeaderText="Date Borrowed"
SortExpression="dateborrowed" />
<asp:BoundField DataField="datereturned" HeaderText="Date Returned"
NullDisplayText="-- not yet returned --" SortExpression="datereturned" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="lendgridviewDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
DeleteCommand="DELETE FROM [LendTable] WHERE [lenid] = #lenid"
InsertCommand="INSERT INTO [LendTable] ([bookid], [department], [EmployeeID], [dateborrowed], [datereturned]) VALUES (#bookid, #department, #EmployeeID, #dateborrowed, #datereturned)"
SelectCommand="SELECT dbo.LendTable.lenid, dbo.LendTable.bookid, dbo.LendTable.department, dbo.LendTable.EmployeeID, dbo.LendTable.dateborrowed, dbo.LendTable.datereturned, dbo.TblBooks.booktitle FROM dbo.LendTable INNER JOIN dbo.TblBooks ON dbo.LendTable.bookid = dbo.TblBooks.bookid"
UpdateCommand="UPDATE [LendTable] SET [bookid] = #bookid, [department] = #department, [EmployeeID] = #EmployeeID, [dateborrowed] = #dateborrowed, [datereturned] = #datereturned WHERE [lenid] = #lenid">
<DeleteParameters>
<asp:Parameter Name="lenid" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="bookid" Type="Int64" />
<asp:Parameter Name="department" Type="String" />
<asp:Parameter Name="EmployeeID" Type="String" />
<asp:Parameter Name="dateborrowed" Type="DateTime" />
<asp:Parameter Name="datereturned" Type="DateTime" />
<asp:Parameter Name="lenid" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="bookid" Type="Int64" />
<asp:Parameter Name="department" Type="String" />
<asp:Parameter Name="EmployeeID" Type="String" />
<asp:Parameter Name="dateborrowed" Type="DateTime" />
<asp:Parameter Name="datereturned" Type="DateTime" />
</InsertParameters>
</asp:SqlDataSource>
</p>
<p>
<asp:HyperLink ID="HyperLink4" runat="server"
NavigateUrl="~/Admin/Returning.aspx">Returning</asp:HyperLink>
</p>
<asp:HyperLink ID="HyperLink5" runat="server"
NavigateUrl="~/Admin/AdminPage.aspx">Back to Admin Page</asp:HyperLink>
<p>
</p>
</asp:Content>
You have to use the Databound event for that...
protected void FormView1_DataBound(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Insert)
{
TextBox dateadded = FormView1.FindControl("dateaddedTextBox") as TextBox;
dateadded.Text = DateTime.Now.ToString("d");
}
}
Edit: You need to pass your Date Column in the inserting method of the DetailsView
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
e.Values["DateColumnName"] = ((TextBox)DetailsView1.FindControl("dateaddedTextBox")).Text;
}
Instead of doing that in your Page_Load() method, try doing it in the Page_PreRender() method.