Is it possible to update GridView with variable number of columns? - c#

I have a GridView linked to a SQL table. Table have unknown or variable number of columns. Both the number of columns and the names of the columns are variable. Is it possible, to setup a dynamic UpdateCommand in the sqlDataSource so that I can update every column? If yes; how?
Code I tried:
<asp:GridView ID="GridView1" AutoGenerateColumns="True" ShowHeaderWhenEmpty ="True" DataSourceID="UpdateSqlDataSource"
CssClass = "table" runat="server" AllowSorting="True" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataKeyNames="UpdateID" ShowFooter="True"
AutoGenerateDeleteButton="true" AutoGenerateSelectButton ="true" AutoGenerateEditButton="true">
<AlternatingRowStyle BackColor="#F7F7F7" />
<Columns>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<SortedAscendingCellStyle BackColor="#F4F4FD" />
<SortedAscendingHeaderStyle BackColor="#5A4C9D" />
<SortedDescendingCellStyle BackColor="#D8D8F0" />
<SortedDescendingHeaderStyle BackColor="#3E3277" />
</asp:GridView>
<asp:SqlDataSource ID ="UpdateSqlDataSource" runat ="server" ConnectionString="<%$ ConnectionStrings:MachineUpdateDataBaseConnectionString %>"
DeleteCommand="DELETE FROM [MachineUpdate] WHERE [UpdateID] = #UpdateID"
SelectCommand="SELECT * FROM [MachineUpdate]" UpdateCommand="UPDATE SET [MachineUpdate] = #MachineUpdate WHERE [UpdateID] = #UpdateID[*] = #* WHERE [UpdateID] = #UpdateID">
<DeleteParameters>
<asp:Parameter Name="UpdateID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>

The UpdateCommand of your SqlDataSource is always static, to generate an dynamic update, your should do it by C# code handling the RowUpdating event of the GridView.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string sqlCommand = "UPDATE YourTable SET ";
foreach (DictionaryEntry item in e.NewValues)
{
// You will need to take care to not update PK, FK, etc
// You will need to handle DB restrictions
// You will need to handle DataTypes (eg: Not set a boolean in a Date column)
sqlCommand = sqlCommand + item.Key + " = " + item.Value + ",";
}
sqlCommand = sqlCommand.TrimEnd(','); // removes the last comma
foreach (DictionaryEntry de in e.Keys)
{
//Assuming that you will have just only one key
// You can get the Key in the GridView.DataKeyNames property as well
sqlCommand = sqlCommand + " WHERE " + de.Key.ToString() + " = " + de.Value.ToString();
}
GridView grd = (GridView)sender;
SqlDataSource ds = (SqlDataSource)grd.DataSourceObject;
ds.UpdateCommand = sqlCommand; // Modify the UpdateCommand of you SqlDataSource
}
Note: Update columns dynamically isn't a good idea, you will have more headache than benefits. But for simple scenarios, the above code could work.

Related

database is showing all 0's when the checked boxes should show one

I am rather new to programming in general. I am creating an webpage where the user selects a process from a sql populated dropdown list. A grid view then populates with the corresponding results with checkboxes. The end user can select a checkbox and that should save the value 1 to the database so that I can retrieve the checked items for another grid view later. Unfortunately it is only populating zeros. How can i fix this?
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkBox1 = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
if (checkBox1.Checked)
{
string updateData = "update AuditChecklist$ set IsSelected = #IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", 1);
cmd.ExecuteNonQuery();
con.Close();
}
else if(!checkBox1.Checked)
{
string updateData = "update AuditChecklist$ set IsSelected = #IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", 0);
cmd.ExecuteNonQuery();
con.Close();
}
}
Tried the following code as suggested but I am still having the same issue. I have included my design and ASP code for further help.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkBox1 = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
string updateData = "update AuditChecklist$ set IsSelected = #IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", checkBox1.Checked ? 1 : 0);
cmd.ExecuteNonQuery();
con.Close();
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource2" ForeColor="#333333" GridLines="None" Height="377px" Width="764px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Select">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="FAST_Screen" HeaderText="FAST Screen" SortExpression="FAST_Screen">
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="Audit_Detail" HeaderText="Audit Detail" SortExpression="Audit_Detail">
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Delete</asp:LinkButton>
</ItemTemplate>
</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="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:QMSAuditConnectionString %>" SelectCommand="SELECT [FAST Screen] AS FAST_Screen, [Audit Detail] AS Audit_Detail, [EPS Process] AS EPS_Process, [IsSelected] FROM [AuditChecklist$] WHERE ([EPS Process] = #EPS_Process)">
<SelectParameters>
<asp:ControlParameter ControlID="LstProcess" Name="EPS_Process" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Design
It seems you set the ThreeState property of CheckBox to true, so it must be changed to false.
It doesn't need write same codes twice only for one check condition.
CheckBox checkBox1 = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
string updateData = "update AuditChecklist$ set IsSelected = :#IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", checkBox1.Checked ? 1 : 0);
cmd.ExecuteNonQuery();
con.Close();
Also it will be better if an update statement has any filter (using where clause).

Update a row in GridView ASP NET doesn't work

I'm new ASP.NET developer and trying to update a row in a GridView. I have try many solution but it don't work. When I update a row, not error message but the update is not taken into account.
<asp:GridView ID="grd_quest" Visible = "False" runat="server" CellPadding="4"
DataSourceID="ERP_questionn" ForeColor="#333333" GridLines="None"
AutoGenerateColumns="False" DataKeyNames="QUE_id">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:BoundField DataField="QUE_id" HeaderText="ID" ReadOnly="True"
SortExpression="QUE_id" ItemStyle-Width="10%" />
<asp:BoundField DataField="QUE_libelle" HeaderText="Libelle"
SortExpression="QUE_libelle" />
</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="ERP_questionn" runat="server"
ConnectionString="<%$ ConnectionStrings:ERPConnectionString %>"
SelectCommand=""
UpdateCommand=
"UPDATE [TR_QUESTION] SET [QUE_libelle] = #QUE_libelle WHERE [QUE_id] = #QUE_id">
<UpdateParameters>
<asp:Parameter Name="QUE_libelle" Type="String" />
<asp:Parameter Name="QUE_id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
The select command is not written here because it changes in function of others list so I write the SelectCommand in C#.
I hope it's clear for you
[EDIT]
I had try an other solution with this in C# :
protected void grd_quest_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
int id = Convert.ToInt32(grd_quest.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)grd_quest.Rows[e.RowIndex];
//TextBox txtname=(TextBox)gr.cell[].control[];
TextBox textadd = (TextBox)row.Cells[2].Controls[0];
//TextBox textadd = (TextBox)row.FindControl("txtadd");
//TextBox textc = (TextBox)row.FindControl("txtc");
grd_quest.EditIndex = -1;
sqlConnection1.Open();
//SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
SqlCommand cmd = new SqlCommand("UPDATE TR_QUESTION SET QUE_libelle = #p_libelle where QUE_id = #p_id ", sqlConnection1);
cmd.Parameters.AddWithValue("#p_id", id);
cmd.Parameters.AddWithValue("#p_libelle", textadd.Text);
cmd.ExecuteNonQuery();
sqlConnection1.Close();
grd_quest.DataBind();
}
But it does not work too, I have an error message who say that :
The data source 'ERP_questionn' does not support updating unless UpdateCommand is specified. I have try : UpdateCommand = "" but it does not work too
[EDIT new try ]
protected void grd_quest_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id = grd_quest.DataKeys[e.RowIndex].Value.ToString();
string libelle = ((TextBox)grd_quest.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
ERP_questionn.UpdateParameters["QUE_id"].DefaultValue = id;
ERP_questionn.UpdateParameters["QUE_libelle"].DefaultValue = libelle;
ERP_questionn.Update();
//ERP_questionn.SelectCommand = DropDownList1.SelectedValue;
}
When I update a row, not error message but the update is not taken into account.
[EDIT]
Maybe that can help,to display my data in my gridView I did this :
protected void lst_facteur_SelectedIndexChanged(object sender, EventArgs e)
{
if (lst_pos.SelectedValue == "1")
{
ERP_questionn.SelectCommand = "select * FROM TR_QUESTION WHERE FAC_id =" + lst_facteur.SelectedValue + " AND QUE_ordreUsine IS NOT NULL";
}
else if (lst_pos.SelectedValue == "2")
{
ERP_questionn.SelectCommand = "select * FROM TR_QUESTION WHERE FAC_id =" + lst_facteur.SelectedValue + " AND QUE_ordreBureau IS NOT NULL";
}
grd_quest.DataBind();
grd_quest.Visible = true;
txt_question.Visible = true;
btn_add_question.Visible = true;
I have always the update problem...
"UPDATE [TR_QUESTION] SET [QUE_libelle] =? WHERE [QUE_id] =?"
As well as this, you have not set an update command event on the gridview.
onrowupdated="CustomersGridView_RowUpdated"
You have to set SelectCommand = "SELECT * FROM [TR_QUESTION]" in HTML Code also:
<asp:GridView ID="grd_quest" runat="server" AutoGenerateColumns="False" DataKeyNames="QUE_id" DataSourceID="ERP_questionn">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="QUE_id" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="QUE_id" />
<asp:BoundField DataField="QUE_libelle" HeaderText="Libelle" SortExpression="QUE_libelle" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="ERP_questionn" runat="server"
ConnectionString="<%$ ConnectionStrings:ERPConnectionString %>"
SelectCommand = "SELECT * FROM [TR_QUESTION]"
UpdateCommand =
"UPDATE [TR_QUESTION] SET [QUE_libelle] = #QUE_libelle WHERE [QUE_id] = #QUE_id">
</asp:SqlDataSource>

Retrieving data from DetailsView

I'm trying to retrieve data from the DetailsView control in order to input them into another database table. I've looked through other questions that others asked but none of their questions could fit into my situation, which is trying to access SQL Database. Ultimately, I couldn't find the answer I require.
Basically, my objective of the codes is to extract the second row of the DetailsView, since the first row are mostly the static headers that do not change. My DetailsView would change upon the selection of a GridView above. Hence, I'm trying to retrieve the data on the second row, explaining my usage of Rows[2] , while I presume that "Cells[]" refers to the columns.
I'm using the following codes to do so.
string insertQuery = "insert into SalesOrders ([pQuotation#], pServices, pQty, pDescription, [p[Price/Unit]], pNetvalue, pProgress, pClientNo values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con)
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text);
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text);
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text);
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text);
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text);
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text);
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
I've been thrown the following exception:
Error:System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index at System.Web.UI.ControlCollection.get_Item(Int32 index) at RealClientPurchase.Button1_Click(Object sender, EventArgs e) in d:\Desktop\RealClientPurchase.aspx.cs:line 27
EDIT:
This is the code behind file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class RealClientPurchase : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
clientnolbl.Text = Session["sClientNo"].ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Desktop\TemporarySter\App_Data\legitdatabase.mdf;Integrated Security=True;Connect Timeout=30");
try
{
con.Open();
SqlCommand cmd;
string insertQuery = "insert into SalesOrders ([pQuotation#], pServices, pQty, pDescription, [p[Price/Unit]], pNetvalue, pProgress, pClientNo values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text);
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text);
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text);
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text);
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text);
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text);
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect",
"alert('Purchase order has been submitted! Kindly proceed to checkout.'); window.location='" +
Request.ApplicationPath + "CurrentCheckout.aspx';", true);
con.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
}
These are the aspx codes:
<%# Page Title="" Language="C#" MasterPageFile="~/ClientPortal.master" AutoEventWireup="true" CodeFile="RealClientPurchase.aspx.cs" Inherits="RealClientPurchase" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Register1ConnectionString %>" SelectCommand="SELECT [qQuotationNo], [qServices], [qQuantity], [qDate] FROM [Quotations] WHERE ([qClientNo] = #qClientNo)">
<SelectParameters>
<asp:SessionParameter Name="qClientNo" SessionField="sClientNo" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:Register1ConnectionString %>" SelectCommand="SELECT [qQuotationNo], [qServices], [qQuantity], [qDescription], [qPricePerQty], [qTotalPayable] FROM [Quotations] WHERE ([qQuotationNo] = #qQuotationNo)">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="qQuotationNo" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Label ID="clientnolbl" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="qQuotationNo" DataSourceID="SqlDataSource1" Height="125px" Width="452px" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="qQuotationNo" HeaderText="Quotation No" InsertVisible="False" ReadOnly="True" SortExpression="qQuotationNo" />
<asp:BoundField DataField="qServices" HeaderText="Services" SortExpression="qServices" />
<asp:BoundField DataField="qQuantity" HeaderText="Quantity" SortExpression="qQuantity" />
<asp:BoundField DataField="qDate" HeaderText="Date" SortExpression="qDate" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<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" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataSourceID="SqlDataSource2" Height="50px" Width="452px" CellPadding="4" ForeColor="#333333" GridLines="None" DataKeyNames="qQuotationNo">
<AlternatingRowStyle BackColor="White" />
<CommandRowStyle BackColor="#D1DDF1" Font-Bold="True" />
<EditRowStyle BackColor="#2461BF" />
<FieldHeaderStyle BackColor="#DEE8F5" Font-Bold="True" />
<Fields>
<asp:BoundField DataField="qQuotationNo" HeaderText="qQuotationNo" SortExpression="qQuotationNo" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="qServices" HeaderText="qServices" ReadOnly="True" SortExpression="qServices" />
<asp:BoundField DataField="qQuantity" HeaderText="qQuantity" SortExpression="qQuantity" ReadOnly="True" />
<asp:BoundField DataField="qDescription" HeaderText="qDescription" SortExpression="qDescription" ReadOnly="True" />
<asp:BoundField DataField="qPricePerQty" HeaderText="qPricePerQty" SortExpression="qPricePerQty" ReadOnly="True" />
<asp:BoundField DataField="qTotalPayable" HeaderText="qTotalPayable" SortExpression="qTotalPayable" ReadOnly="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:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
<br />
<br />
<br />
</asp:Content>
I've found the solution.
I changed the fields in the database table to exclude "#" and "[" or "]"
It appears these signs do not function well in a SQL statement.
Revamped codes are as follows, and they do work.
SqlCommand cmd;
string insertQuery = "INSERT INTO SalesOrders (pQuotationNo, pServices, pQty, pDescription, pPricePerQty, pNetvalue, pProgress, pClientNo) values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
cmd.ExecuteNonQuery();
Can you try DetailsView1.Rows[0].Cells[0].Text?
Since your DetailsView has BoundFields only, this should work.
Regards

Id of gridview shows wrong sequence

I have a gridview which has columns (Id,Task,Reward,Time Allotted,Uploader)..I can insert data into the gridview successfully untill page no 13 with taskId 118,but after that the data starts to show up at page no 1 right after TaskId 7.
So the sequence is like ....5,6,7,119,120,121,122,8,9,10.....
So all the new data gets inserted between 7 and 8.Why is that?how can i correct this?
I don;t think this is a code fault but still here is mine:
protected void btnPost_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["EasyRozMoney_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTasks", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", txtTitle.Text);
cmd.Parameters.AddWithValue("#Body", txtBody.Text);
cmd.Parameters.AddWithValue("#Reward", txtRewards.Text);
cmd.Parameters.AddWithValue("#TimeAllotted", txtTime.Text);
cmd.Parameters.AddWithValue("#PosterName", txtPoster.Text);
con.Open();
cmd.ExecuteNonQuery();
lblStatus.Text = "Task Posted Successfully.";
}
here is the gridview:
<asp:GridView ID="GridView1" runat="server" Width="936px" AllowPaging="True" AutoGenerateColumns="False" CellPadding="3" DataSourceID="SqlDataSource1" OnRowCommand="GridView1_RowCommand" style="text-align: center" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellSpacing="2" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="TaskId" HeaderText="TaskId" InsertVisible="False" ReadOnly="True" SortExpression="TaskId" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Body" HeaderText="Body" SortExpression="Body" Visible="false" />
<asp:BoundField DataField="Reward" HeaderText="Reward(Rs)" SortExpression="Reward" />
<asp:BoundField DataField="TimeAllotted" HeaderText="Time(Min)" SortExpression="TimeAllotted" />
<asp:BoundField DataField="PosterName" HeaderText="Uploader" SortExpression="PosterName" />
<asp:ButtonField ButtonType="Button" CommandName="Select" Text="Perform Task" ControlStyle-ForeColor="White" ControlStyle-Font-Bold="true">
<ControlStyle BackColor="#CC6600" Font-Bold="True" ForeColor="White"></ControlStyle>
</asp:ButtonField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#CC6600" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EasyRozMoney_ConnectionString %>" SelectCommand="SELECT * FROM [Task]"></asp:SqlDataSource>
My Table in sql is as below:
Create table Task
(
TaskId int Identity(1,1),
Title varchar(100),
Body varchar(500),
Reward decimal(4,2),
TimeAllotted int,
PosterName varchar(100)
)
my stored procedure :
Create proc spTasks
#Title varchar(100),
#Body varchar(500),
#Reward decimal(4,2),
#TimeAllotted int,
#PosterName varchar(100)
as
begin
Insert into Task values(#Title,#Body,#Reward,#TimeAllotted,#PosterName)
end
You can change the default sort on your select statement of your data source. If you want recent records to show up in the end: sort by default, if you want them to display first in your grid: sort by descending order.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:EasyRozMoney_ConnectionString %>"
SelectCommand="SELECT * FROM [Task] ORDER BY TASKID"></asp:SqlDataSource>
On a note, you should use select '*' only in test cases. In real world scenarios, this will cause a performance blow doing a table scan. Inside your select statement, select only desired columns that are needed for display in your UI.
As others have pointed our, do check your database column that its of type int or varchar, if the later you can cast your column as an int, or better create it as an int altogether.

Adding All Rows Checkbox for Unknown Gridview Data Source

I have a Gridview like this.
<asp:GridView ID="GridView1" runat="server"
Width="16px" BackColor="White" BorderColor="#E7E7FF"
BorderStyle="None" BorderWidth="1px" CellPadding="3"
GridLines="Horizontal" Height="16px" >
<AlternatingRowStyle BackColor="#F7F7F7" />
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<sortedascendingcellstyle backcolor="#F4F4FD" />
<sortedascendingheaderstyle backcolor="#5A4C9D" />
<sorteddescendingcellstyle backcolor="#D8D8F0" />
<sorteddescendingheaderstyle backcolor="#3E3277" />
<SortedAscendingCellStyle BackColor="#F4F4FD"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#5A4C9D"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#D8D8F0"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#3E3277"></SortedDescendingHeaderStyle>
</asp:GridView>
Programaticly, i adding a data source this Gridview.
protected void SendToGridview_Click(object sender, EventArgs e)
{
Calculate.Visible = true;
MV_Label.Visible = true;
RISK_Label.Visible = true;
string strQuery;
string ConnectionString = ConfigurationManager.ConnectionStrings["ora"].ConnectionString;
OracleConnection myConnection = new OracleConnection(ConnectionString);
strQuery = #"SELECT A.HESAP_NO, A.TEKLIF_NO1 || '/' || A.TEKLIF_NO2 AS TEKLIF, A.MUS_K_ISIM AS MUSTERI,
B.MARKA, C.SASI_NO, C.SASI_DURUM, D.TAS_MAR, NVL(RISK_SASI(A.TEKLIF_NO1, A.TEKLIF_NO2, C.URUN_SIRA_NO, C.SIRA_NO),0) AS RISK,
NVL(MV_SASI(A.TEKLIF_NO1, A.TEKLIF_NO2, C.SIRA_NO, C.URUN_SIRA_NO, SYSDATE),0) AS MV
FROM S_TEKLIF A, S_URUN B, S_URUN_DETAY C, KOC_KTMAR_PR D
WHERE A.TEKLIF_NO1 || A.TEKLIF_NO2 = B.TEKLIF_NO1 || B.TEKLIF_NO2
AND A.TEKLIF_NO1 || A.TEKLIF_NO2 = C.TEKLIF_NO1 || C.TEKLIF_NO2
AND B.SIRA_NO = C.URUN_SIRA_NO
AND B.DISTRIBUTOR = D.DIST_KOD
AND B.MARKA = D.MARKA_KOD
AND B.URUN_KOD = D.TAS_KOD ";
string param = "";
foreach (ListItem l in CheckBoxList1.Items)
{
if (l.Selected)
{
param += string.Format("'{0}'", l.Value);
param += ",";
}
}
param = param.Remove(param.Length - 1);
strQuery = strQuery + " AND A.HESAP_NO IN (" + param + ")";
OracleCommand myCommand = new OracleCommand(strQuery, myConnection);
myCommand.CommandType = System.Data.CommandType.Text;
myCommand.Connection = myConnection;
myCommand.CommandText = strQuery;
myConnection.Open();
OracleDataReader dr = myCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
GridView1.DataSource = dr;
GridView1.DataBind();
GridView1.Visible = true;
myConnection.Close();
}
This is my Gridview looks;
What i want is, i want to add checkboxes column after RISK column and MV column.
I mean, columns looks like, HESAP_NO, TEKLIF, MUSTERI, MARKA, SASI_NO, SASI_DURUM, TAS_MAR, RISK, (CheckBoxes), MV, (Checkboxes). Totaly should be 11 column.
And i want all checkboxes is checked as a default.
How can i do that?
I read this article, but in this article Gridview a normal data source. I adding programaticly.
You are going to have to switch AutoGenerated columns off and used defined ones instead:
<asp:GridView ID="GridView1" runat="server" Width="16px" BackColor="White"
BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
CellPadding="3" GridLines="Horizontal" Height="16px" AutoGenerateColumns="false">
<!-- put your style stuff here -->
<asp:BoundField HeaderText="Text" DataField="HESAP_NO" />
<asp:BoundField HeaderText="Text" DataField="TEKLIF" />
<asp:BoundField HeaderText="Text" DataField="MUSTERI" />
<asp:BoundField HeaderText="Text" DataField="MARKA" />
<asp:BoundField HeaderText="Text" DataField="SASI_NO" />
<asp:BoundField HeaderText="Text" DataField="SASI_DURAM" />
<asp:BoundField HeaderText="Text" DataField="TAS_MAR" />
<asp:BoundField HeaderText="Text" DataField="RISK" />
<asp:BoundField HeaderText="Text" DataField="Text" />
<asp:CheckBoxField DataField="NameCheckBoxField1" HeaderText="NameCheckBoxField1" />
<asp:BoundField HeaderText="Text" DataField="MV" />
<asp:CheckBoxField DataField="NameCheckBoxField2" HeaderText="NameCheckBoxField2" />
</asp:GridView>
You will also need to change your SQL to return two fields that the CheckBoxField can map to. Those fields should contain a bit field with true set for all cases. This will allow the data to be automatically bound to the CheckBoxField and checked by default.
EG:
SELECT
-- all our fields
'NameCheckBoxField1' = 0x1,
'NameCheckBoxField2' = 0x1
FROM
-- etc...

Categories

Resources