Fail to save multiple data from gridview to database - c#

Here is the HTML markup of the gridview.I mean aspx page
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false"
OnRowCreated="Gridview1_RowCreated" Height="145px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" DataTextField="CURRENCY_NAME"
DataValueField="CURRENCY_ID">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 4">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true" DataTextField="BRAND_NAME"
DataValueField="BRAND_ID">
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="BtnSave" runat="server" Text="Save All" OnClick="BtnSave_Click" />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>`
Here is the code behind to save the data into the database
private void InsertRecords(StringCollection sc)
{
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
const string sqlStatement = "INSERT INTO GridViewDynamicData (Field1,Field2,Field3,Field4) VALUES";
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
}
}
using (OracleConnection strConn = GetConnection())
{
strConn.Open();
OracleCommand cmd = new OracleCommand(sb.ToString(), strConn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
lblMessage.Text = "Records successfully saved!";
}
}
protected void BtnSave_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");
//get the values from TextBox and DropDownList
//then add it to the collections with a comma "," as the delimited values
sc.Add(string.Format("{0},{1},{2},{3}", box1.Text, box2.Text, ddl1.SelectedItem.Text, ddl2.SelectedItem.Text));
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
My database table is here
CREATE TABLE ERP.GRIDVIEWDYNAMICDATA
(
FIELD1 VARCHAR2(500 BYTE),
FIELD2 VARCHAR2(500 BYTE),
FIELD3 VARCHAR2(500 BYTE),
FIELD4 VARCHAR2(500 BYTE)
)
When I am running this project it is showing error "ORA-00911: invalid character". I don't know what is wrong. Any help will be appreciated.

I am not having enough reputation to comment, so I am posting my research as an answer.
Most probable cause is using ; in query building.
Remove ;(semi-colon) from the end of SQL string.
From the SQL query you are building from the code.
With semicolon (May causing the error)
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
Without Semicolon (Should try this)
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}') ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
Or
Your string may not have straight ' single quotes. Try to write that again. (It seems OK though in your code posted along with question. But nothing wrong in verifying.)
References:
ORA-00911: invalid character
https://community.oracle.com/thread/2511511
http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/hol08/dotnet/getstarted-c/getstarted_c_otn.htm

Related

How to preserve value of textboxes using TemplateFields in GridView

I have a GridView that lists data from my mysql database table. In addition, I created two TemplateFields to the GridView. The first TemplateField displays the data from database tables and the second TemplateView contains 1x asp:TextBox (a.k.a quantity) and 2x asp:Buttons (a.k.a +/- buttons which change the value inside the quantity TextBox. In addition to binding the GridView on PageLoad event, I also have a search TextBox which filters the rows displayed in the GridView. Here is the code behind for the search GridView TextBox:
private void SearchProducts()
{
string constr = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
string sql = "SELECT logic_code,description,image_location,product_group,supplier_number,sequence,unit_code,unit_of_price,location,sales_date,price_pref,special_price,in_stock,total_inventory,new_products FROM products";
if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
{
sql += " WHERE description LIKE " + "'%" + txtSearch.Text + "%'";
}
cmd.CommandText = sql;
cmd.Connection = con;
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
dt.Columns.Add(new DataColumn("QUANTITY"));
GridView1.DataBind();
//TextBox qty4 = GridView1.FindControl("qty_ordered") as TextBox;
// for(int i = 0; i < GridView1.Rows.Count; i++)
//{
// Label test222 = (Label)GridView1.Rows[i].FindControl("test2");
// TextBox qty2 = (TextBox)GridView1.Rows[i].FindControl("qty_ordered");
// if (ViewState["purchased"] != null)
// {
// qty2.Text = ViewState["purchased"].ToString();
// }
// //test222.Text = qty2.Text;
//}
}
}
}
//foreach(GridViewRow rows in GridView1.Rows)
{
//Label test22 = rows.FindControl("test2") as Label;
//TextBox qty = rows.FindControl("qty_ordered") as TextBox;
//if (ViewState["purchased"] != null)
//{
//qty.Text = ViewState["purchased"].ToString();
//}
}
}
First I tried saving each Rows TextBox.Text to ViewState but wasn't successful, then I tried dynamically adding a new column to DataTable before DataBind() but that also went south... The Buttons (+/-) and TextBox work fine when PostBack is from the buttons themselves. However, as soon as I filter the GridView using the c# code above, The TextBoxes all turn back to "0" and lose their values. I think that adding the new column dynamically is the way to go, I'm just not sure how to save/update the values without creating EditTemplateFields.
Here is my asp.net code for the GridView:
<asp:GridView id="GridView1" EnableViewState="true" AutoGenerateColumns="false" PageSize="100" ShowHeader="false" DataKeyNames="logic_code" AllowPaging="true" runat="server" Style="width:100%;margin-top:45px;">
<Columns>
<asp:BoundField DataField="QUANTITY" runat="server" readonly="true" />
<asp:TemplateField HeaderText="Product_Template" runat="server">
<ItemTemplate>
<asp:label id="supplier_number" runat="server" Style="font-weight:bold;font-size:28px;" Text='<%# Eval("supplier_number")%>' /> <asp:label id="total_inventory" runat="server" Text='<%# Eval("total_inventory")%>' Style="float:right;" />
<br />
<asp:label id="sequence" runat="server" Text='<%# Eval("sequence")%>' Style="float:right;" />
<br />
<asp:Image id="product_image" runat="server" Height="320px" Width="320px" ImageUrl='<%# Eval("image_location")%>' />
<br />
<asp:label id="product_description" runat="server" Text='<%# Eval("description")%>' Style="white-space:nowrap;" /> &nbsp<asp:label id="unit_of_price" runat="server" Text='<%# Eval("unit_of_price")%>' Style="float:right;font-size:10px;margin-top:16px;margin-right:5px;margin-left:1px;" /><asp:label id="price_pref" runat="server" Text='<%# "$" + Eval("price_pref")%>' Style="float:right;font-size:22px;font-weight:bold;" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product_Template1" runat="server" ItemStyle-Width="150px">
<ItemTemplate runat="server">
<asp:Button id="add" runat="server" Text="+" Width="45px" Style="float:right;" OnClick="addClicked" autopostback="true" UseSubmitBehavior="true"></asp:Button> <asp:Button id="subtract" runat="server" Text="-" Style="float:right;" OnClick="subtractClicked" autopostback="true" UseSubmitBehavior="true" Width="45px"></asp:Button>
<asp:TextBox id="qty_ordered" runat="server" Text="0" Enabled="false" Style="float:right;" Width="57px" EnableViewState="true" ReadOnly="true" />
<asp:Label id="unit_display" runat="server" Style="float:right;" />
<asp:Label id="sequenceID" runat="server" Text='<%# Eval("sequence")%>' Visible="false" Enabled="false" />
<asp:Label id="unit_code1" runat="server" Text='<%# Eval("unit_code")%>' Visible="false" Enabled="false" />
<asp:Label id="supplier_no" runat="server" Text='<%# Eval("supplier_number")%>' Visible="false" Enabled="false" />
<asp:Label id="total_inventory1" runat="server" Text='<%# Eval("total_inventory")%>' Visible="false" Enabled="false" />
<asp:Label id="logic_code1" runat="server" Text='<%# Eval("logic_code")%>' Visible="false" Enabled="false" />
<asp:Label id="unit_of_price1" runat="server" Text='<%# Eval("unit_of_price")%>' Visible="false" Enabled="false" />
<asp:Label id="price_pref1" runat="server" Text='<%# Eval("price_pref")%>' Visible="false" Enabled="false" />
<asp:Label id="special_price1" runat="server" Text='<%# Eval("special_price")%>' Visible="false" Enabled="false" />
<asp:Label id="description1" runat="server" Text='<%# Eval("description")%>' Visible="false" Enabled="false" />
<asp:Label id="tester" runat="server" Text='<%# Eval("description")%>' Visible="false" Enabled="false" />
<asp:Label id="test2" runat="server" Visible="true" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the code behind for how I populate the GridView on PageLoad when the GridView is not getting filtered by the search box:
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand("SELECT logic_code,description,image_location,product_group,supplier_number,sequence,unit_code,unit_of_price,location,sales_date,price_pref,special_price,in_stock,total_inventory,new_products FROM products"))
{
using (MySqlDataAdapter da = new MySqlDataAdapter())
{
cmd.Connection = con;
da.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
da.Fill(dt);
GridView1.DataSource = dt;
dt.Columns.Add(new DataColumn("QUANTITY", System.Type.GetType("System.Double")));
GridView1.DataBind();
con.Close();
}
}
}
}
}
And PageLoad is here:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindGrid();
}
if (string.IsNullOrEmpty(txtSearch.Text))
{
//txtSearch.Attributes.Add("CssStyle", "cursor");
txtSearch.Attributes.Add("placeholder", " Showing All Products");
}
//foreach(GridViewRow row in GridView1.Rows)
//{
// if (IsPostBack)
// {
// if (ViewState["purchased"].ToString() != null)
// {
// qty.Text = ViewState["purchased"].ToString();
// }
// }
//}
}
I also have EnableViewState = "true" at the top of page.
***Note: with the code below on each button (+/-), the ViewState seems to save fine as my labels get populated appropriately by reading the ViewState even when postback. However, the values of the labels (ViewState value) get reset once I call the private void SearchProducts()
for(int i = 0; i < GridView1.Rows.Count; i++)
{
Label test222 = (Label)GridView1.Rows[i].FindControl("test2");
TextBox qty2 = (TextBox)GridView1.Rows[i].FindControl("qty_ordered");
ViewState["purchased"] = qty2.Text;
test222.Text = ViewState["purchased"].ToString();
}
and heres 2 snapshots: (as you can see, when I enter "Benus" inside the search textbox, the gridview gets filtered correctly, but all the TextBox values gets reset to "0")

Bulk Edit Update Multiple Rows in ASP.Net GridView using CheckBoxes

you can see VT_AClReport Table design In the below HTML Markup I have a simple ASP.Net GridView with 3 columns.
First column containing the CheckBox, second column containing a Label for display ID and Access Path of the folder respectively and the third column containing a Label and DropDownList for display and edit status of the folder respectively.
Here I am using GridView with paging to display the data, and the data is about millions of rows. When I click on submit button to update the checkbox selected rows, execution time is taking too much to update the rows in table.
For Example: for 5000 rows = 26 min.
Can anyone help me to resolve this issue and reduce the execution time to update all the records within few seconds.
Please see the code:
<asp:GridView ID="gvACLReport" runat="server" AutoGenerateColumns="False"CssClass="mgrid" EmptyDataText="No Records Exists..." DataKeyNames="ACLId" ShowFooter="True" HorizontalAlign="Center" Width="100%" AllowPaging="True" EnableSortingAndPagingCallback="True" PageSize="500" AllowSorting="True" Visible="False" onpageindexchanging="gvACLReport_PageIndexChanging" EnableSortingAndPagingCallbacks="True">
<AlternatingRowStyle CssClass="mgridalt" />
<PagerSettings PageButtonCount="10000" />
<PagerStyle CssClass="gridview" HorizontalAlign="Center"></PagerStyle>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAllACLReport" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkACLReport" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged"/>
</ItemTemplate>
<ItemStyle Width="20px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="ACL Id">
<ItemTemplate>
<asp:Label ID="lblACLId" runat="server" Text='<%# Eval("ACLId") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="20px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Access Path">
<ItemTemplate>
<asp:TextBox ID="lblAccessPathACL" runat="server" Rows="3" Width="400px" Text='<%# Eval("AccessPath") %>'ReadOnly="True" TextMode="MultiLine" BorderStyle="None" BorderWidth="0px" BackColor="Transparent"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Directory Name">
<ItemTemplate>
<asp:TextBox ID="lblDirectoryName" runat="server" Rows="3" Width="400px" Text='<%# Eval("DirectoryName") %>'ReadOnly="True" TextMode="MultiLine" BorderStyle="None" BorderWidth="0px" BackColor="Transparent"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="User Group">
<ItemTemplate>
<asp:Label ID="lblUserGroup" runat="server" Text='<%# Eval("UserGroup") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="mgridheader" />
<RowStyle CssClass="mgriditem" />
</asp:GridView>
//Please check this the table contain the drop down list to update the status and submit and clear button
<table id ="tableChangeStatus" align="center" width="100%"
class="body style1" cellspacing="4" style="border-color: #808080;
border-style: solid; border-width: 1px; table-layout: auto;"
runat="server" visible="False">
<tr runat="server">
<td align="left" runat="server">
Status:
</td>
<td runat="server">
<asp:DropDownList ID="ddlChangeStatus" AutoPostBack="True" AppendDataBoundItems="True"
runat="server" Width="200px" DataSourceID="SDSChangeStatus" DataTextField="Status"
DataValueField="StatusId">
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SDSChangeStatus" runat="server" ConnectionString="<%$ ConnectionStrings:gtsgeneralconn %>"
SelectCommand="VT_getStatusList" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="ddlChangeStatus"
Display="Dynamic" ErrorMessage="Select Status" InitialValue="0" SetFocusOnError="True">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr runat="server">
<td align="center" colspan="2" runat="server">
<asp:Button ID="btnChangeStatus" runat="server" Text="Submit" CausesValidation="False"
onclick="btnChangeStatus_Click"
/>
<asp:Button ID="btnChangeClear" runat="server" Text="Clear"
CausesValidation="False" onclick="btnChangeClear_Click"
/>
</td>
</tr>
</table>
Code Behind:
protected void ChangeStatusGlobalSensitiveNonSensitiveReport()
{
int rowsAffected = 0;
foreach (GridViewRow row in gvGlobalSensitive.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox().FirstOrDefault().Checked;
if (isChecked)
{
using (SqlConnection con = new SqlConnection(cs))
{
cmd = new SqlCommand("VT_ACLReportChangeStatus", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 3600;
cmd.Parameters.AddWithValue("#ChangeStatus", ddlChangeStatus.SelectedItem.Text.ToString());
cmd.Parameters.AddWithValue("#ACLId", row.Cells[1].Controls.OfType<Label>().FirstOrDefault().Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
rowsAffected++;
}
}
}
lblUpdatedRowsMsg.Text = rowsAffected + " Rows updated!!";
lblUpdateMsg.Text = "Detail Saved Successfully!!";
gvGlobalSensitive.Visible = false;
tableChangeStatus.Visible = false;
divReport.Visible = false;
}
if (rowsAffected == 0)
{
lblUpdateMsg.Text = "Please select the check box to update the status!!";
lblUpdatedRowsMsg.Text = rowsAffected + " Rows updated!!";
}
}
Stored Procedure
ALTER PROCEDURE [dbo].[VT_ACLReportChangeStatus]
(
#ChangeStatus nvarchar(50)=null,
#ACLId int
)
AS
// Exec VT_ACLReportChangeStatus 'Complete',34
BEGIN
UPDATE VT_ACLReport SET Status = #ChangeStatus WHERE ACLId = #ACLId
End
Replace the UPDATE statement in your stored procedure with T-SQL given below.
I am assuming ACLId is the primary key with a clustered index and you have an index on Status column. You would be better off if you create another index on ACLId and include column Status in it since that will really speed up the lookup in UPDATE statement.
In this T-SQL, updates are happening in batches of 1000 records rather than updating the whole data set. You can play around with changing the value of 100 to something like 500 or even less to come up with the best update batch.
DECLARE #numberOfRowsUpdated INT = 1000, #maxRowsToUpdate INT = 1000;
BEGIN TRY
BEGIN TRAN
WHILE (#numberOfRowsUpdated > 0)
BEGIN
UPDATE TOP (#maxRowsToUpdate) VT_ACLReport SET Status = #ChangeStatus
WHERE ACLId = #ACLId and Status <> #ChangeStatus;
SET #numberOfRowsUpdated = ##ROWCOUNT;
END
if ##trancount > 0
COMMIT TRAN
END TRY
BEGIN CATCH
if ##trancount > 0
ROLLBACK TRAN
-- log and raise error
END CATCH
I solved this problem by maintaining View State, Preserving all checked checkbox state and storing in view state.
then concatenating all the id's in one variable.
protected void gvACLReport_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
PaginateTheData(gv);
gvACLReport.PageIndex = e.NewPageIndex;
UpdateACLReport();
}
protected void PaginateTheData(GridView gvAll)
{
List<int> list = new List<int>();
if (ViewState["SelectedRecords"] != null)
{
list = (List<int>)ViewState["SelectedRecords"];
}
foreach (GridViewRow row in gvAll.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chkReport");
var selectedKey = int.Parse(gvAll.DataKeys[row.RowIndex].Value.ToString());
if (chk.Checked)
{
if (!list.Contains(selectedKey))
{
list.Add(selectedKey);
}
}
else
{
if (list.Contains(selectedKey))
{
list.Remove(selectedKey);
}
}
}
ViewState["SelectedRecords"] = list;
}
}
protected void ChangeStatusACLReport()
{
int rowsAffected = 0;
List<int> list = ViewState["SelectedRecords"] as List<int>;
string ACLId = "";
if (list != null)
{
foreach (int id in list)
{
ACLId = ACLId + id.ToString() + ",";
rowsAffected++;
}
}
else
{
foreach (GridViewRow row in gvACLReport.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
ACLId = ACLId + row.Cells[1].Controls.OfType<Label>().FirstOrDefault().Text + ",";
rowsAffected++;
}
}
}
}
if (rowsAffected == 0)
{
lblUpdateMsg.Text = "Please select the check box to update the status!!";
lblUpdatedRowsMsg.Text = rowsAffected + " Rows updated!!";
}
else
{
ACLId = ACLId.ToString().Trim(',');
using (SqlConnection con = new SqlConnection(cs))
{
cmd = new SqlCommand("VT_ACLReportChangeStatus", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 3600;
//cmd.Parameters.AddWithValue("#ChangeStatus", ddlChangeStatus.SelectedItem.Text.ToString());
//cmd.Parameters.AddWithValue("#ACLId", ACLId);
cmd.Parameters.Add(new SqlParameter("#ACLId", SqlDbType.NVarChar,-1));
cmd.Parameters.Add(new SqlParameter("#ChangeStatus", SqlDbType.NVarChar, 50));
cmd.Parameters["#ACLId"].Value = ACLId;
cmd.Parameters["#ChangeStatus"].Value = ddlChangeStatus.SelectedItem.Text.ToString();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
lblUpdatedRowsMsg.Text = rowsAffected + " Rows updated!!";
lblUpdateMsg.Text = "Detail Saved Successfully!!";
gvACLReport.Visible = false;
tableChangeStatus.Visible = false;
divReport.Visible = false;
// DeleteCompleteACLReport(ACLId);
}

Reordering Columns in a Gridview Dynamically

I have a gridview I'm trying to reorder the columns for, but I'm getting an object not found error.
The code works when I don't include the code under "//code to move columns", but when I include that code, I get an object not found error that "s += txtAD.Text.Trim();" object reference is not set to an instance. It's weird because no matter which columns I switch, it always throws the error that it can't find column 1.
Any ideas?
My HTML:
<asp:GridView ID="gridviewtxSLds" ClientIDMode="Static" runat="server" CssClass="gridclassscrolledtx" CellPadding="0" ForeColor="#333333" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Metric">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("item") %>'
ID="txtctrltype" class="modalpopup2" AutoPostBack="false"></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="AD">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("AD") %>'
ID="txtAD" onfocus="blur()" class="txttime" AutoPostBack="false" ReadOnly="false"></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="BD">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("BD") %>'
ID="txtBD" onfocus="blur()" class="txttime" AutoPostBack="false" ReadOnly="false"></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="CD">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("CD") %>'
ID="txtCD" onfocus="blur()" class="txttime" AutoPostBack="false" ReadOnly="false"></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
code in codebehind to fill gridview
using (var cmdtx2 = new SqlCommand(sqlcmd, conn))
{
DataTable dv = new DataTable();
SqlDataAdapter db = new SqlDataAdapter(cmdtx2);
//code to move columns
var columnMove = gridviewtxSLds.Columns[3];
gridviewtxSLds.Columns.RemoveAt(3);
gridviewtxSLds.Columns.Insert(2, columnMove);
db.Fill(dv);
gridviewtxSLds.DataSource = dv;
gridviewtxSLds.DataBind();
}
Update code, which throws the error:
protected void Bulk_Insert(object sender, EventArgs e)
{
var timeinitid = hfptstate.Value;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < gridviewtxSLds.Rows.Count; i++)
{
#region textbox declarations
TextBox txtitem = gridviewtxSLds.Rows[i].FindControl("txtctrltype") as TextBox;
TextBox txtAD = gridviewtxSLds.Rows[i].FindControl("txtAD") as TextBox;
TextBox txtBD = gridviewtxSLds.Rows[i].FindControl("txtBD") as TextBox;
TextBox txtCD = gridviewtxSLds.Rows[i].FindControl("txtCD") as TextBox;
#endregion textbox declarations
#region command string
string s = "update 1874tx set AD";
s += "='";
//following line throws the error
s += txtAD.Text.Trim();
s += "', ";
s += "BD";
s += "='";
s += txtBD.Text.Trim();
s += "', ";
s += "CD";
s += "='";
s += txtCD.Text.Trim();
s += "' where item";
s += "='";
s += txtitem.Text.Trim();
s += "';";
#endregion
sb.Append(s.ToString());
SqlCommand cmd = new SqlCommand(sb.ToString(), con);
con.Open();
cmd.ExecuteNonQuery();
}
}
Edit: And before anyone comments on concatenation of SQL queries, I know, and for this specific use it doesn't matter.

Save state of checkbox in gridview when changed to edite mode

When I am clicking on imagebutton in my gridview, some cells become editable
but, it loses all the checkboxs values that in the gridview.
Is there a way to save these values?
I made a function who gets the checkboxes values from my xml but, when I call the function inside the command era it's not working.
When I call that function in other imagebutton command era in the gridview which doesn't make some cells editable, that works and the function runs and the values from the xml shown on the checkboxes.
Thanks
<asp:GridView style="direction:rtl; " ShowHeader="False" BorderColor="White" BorderWidth="2px" HeaderStyle-BackColor="#926c3f" HeaderStyle-Font-Bold="false" RowStyle-BorderColor="White" ID="GridView1" runat="server" DataSourceID="XmlDataSource1" AutoGenerateColumns="False" CssClass="auto-style100" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowCommand="GridView1_SelectedIndexChanged" OnRowCancelingEdit="GridView1_SelectedIndexChanged" OnRowEditing="GridView1_SelectedIndexChanged" AllowSorting="True">
<Columns>
<asp:TemplateField HeaderText=" שם משחק" ItemStyle-Width="200px" >
<ItemTemplate >
<asp:Label ID="NameLabel" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "gameName").ToString())%>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="nameTB" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "gameName").ToString())%>'> </asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="קוד משחק" ItemStyle-Width="85px">
<ItemTemplate>
<asp:Label ID="codeLabel" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "gameCode").ToString())%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="הגדרות" ItemStyle-Width="70px">
<EditItemTemplate>
<asp:ImageButton ID="cancelImageButton" runat="server" ImageUrl="~/images/cancel.png" CommandName="cancel" OnClientClick="showWhoIsPublish" />
<asp:ImageButton ID="approveImageButton" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' runat="server" ImageUrl="~/images/approve.png" CommandName="approve" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="settingsImageButton" runat="server" CssClass="buttons" ImageUrl="~/images/אייקון הגדרות.png" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' CommandName="edit" OnClientClick="showWhoIsPublish" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="עריכה" ItemStyle-Width="70px" >
<ItemTemplate>
<asp:ImageButton ID="editImageButton" runat="server" CssClass="buttons" ImageUrl="~/images/אייקון עריכה.png" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' CommandName="editQ" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="מחיקה" ItemStyle-Width="70px">
<ItemTemplate>
<asp:ImageButton ID="deleteImageButton" CssClass="buttons" OnClick="doDelete_Click" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' runat="server" ImageUrl="~/images/אייקון מחיקה.png" CommandName="deleteRow" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" הגבלת זמן" ItemStyle-Width="90px" >
<EditItemTemplate>
<asp:DropDownList ID="DropDownListT" AppendDataBoundItems="True" runat="server" >
<asp:ListItem> 10 שניות</asp:ListItem>
<asp:ListItem> 20 שניות</asp:ListItem>
<asp:ListItem> 30 שניות</asp:ListItem>
<asp:ListItem> 40 שניות</asp:ListItem>
<asp:ListItem> 50 שניות</asp:ListItem>
<asp:ListItem> 60 שניות</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate >
<asp:Label ID="Time" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "time").ToString())%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="פרסום" ItemStyle-Width="60px">
<ItemTemplate>
<asp:CheckBox runat="server" ID="Checkbox1" CssClass="buttons1" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' AutoPostBack="True" OnCheckedChanged="PublishYesNo_CheckedChanged" ViewStateMode="Inherit" EnableViewState="True" Checked="False" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void GridView1_SelectedIndexChanged(object sender, GridViewCommandEventArgs e)
{
showWhoIsPublish();
ImageButton i = (ImageButton)e.CommandSource;
// אנו מושכים את האי די של הפריט באמצעות מאפיין לא שמור במערכת שהוספנו באופן ידני לכפתור-תמונה
string theId = i.Attributes["theItemId"];
Session["theId"] = theId;
XmlDocument xmlDoc = XmlDataSource1.GetXmlDocument();
switch (e.CommandName)
{
//אם נלחץ על כפתור מחיקה יקרא לפונקציה של מחיקה
case "deleteRow":
popOfDelete.Visible = true;
string deleteId = (string)Session["theId"];
string theGameNameDelete = Server.UrlDecode(xmlDoc.SelectSingleNode("//game[#id='" + (string)Session["theId"] + "']/gameName").InnerXml);
nameOfGameDelete.Text = "'" + theGameNameDelete + "' " + "?";
showWhoIsPublish();
break;
case "editQ":
string editId = (string)Session["theId"];
string theGameNameEdit = xmlDoc.SelectSingleNode("//game[#id='" + (string)Session["theId"] + "']/gameName").InnerXml;
Session["nameOfEdit"] = theGameNameEdit;
Response.Redirect("Default3.aspx");
break;
case "edit":
addNameTB.Text = "jg";
showWhoIsPublish();
break;
case "cancel":
GridView1.DataBind();
showWhoIsPublish();
break;
case "approve":
GridViewRow gvRow = (GridViewRow)(i.Parent.Parent);
string ApproveId = (string)Session["theId"];
int index = gvRow.RowIndex;
string myName = ((TextBox)GridView1.Rows[index].FindControl("nameTB")).Text;
string myValue = ((DropDownList)GridView1.Rows[index].FindControl("DropDownListT")).Text;
xmlDoc.SelectSingleNode("//game[#id='" + ApproveId + "']/gameName").InnerText = Server.UrlEncode(myName);
xmlDoc.SelectSingleNode("//game[#id='" + ApproveId + "']/time").InnerText = Server.UrlEncode(myValue);
XmlDataSource1.Save();
// יציאה ממצב של עריכה
GridView1.EditIndex = -1;
// ריענון הגריד ויו
GridView1.DataBind();
showWhoIsPublish();
break;
}
}
protected void showWhoIsPublish()
{
//סימון מה שמפורסם
XmlDocument xmlDoc = XmlDataSource1.GetXmlDocument();
XmlNodeList myListPublish = xmlDoc.SelectNodes("/games/user[#id='" + Session["id"] + "']/game/#isPublish");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkItem = (CheckBox)GridView1.Rows[i].FindControl("Checkbox1");
if (myListPublish.Item(i).InnerXml == "yes")
{
chkItem.Checked = true;
}
else
{
chkItem.Checked = false;
}
}
}

GridView_RowUpdating not firing

I have Gridview with ItemTemplate and EditItemTemplate:
But when i click "Ok" button, nothing happens. I tried to put trace point on RowUpdating event and click "Ok" button, but its not even triggered. I assume, that problem could be in the same "Id" of ItemTemplate and EditItemTemplate lbl_first_fl. But earlier this worked fine, the only thing was changed - i updated Visual studio to 2015 and changed Windows to 8. So i installed VS 2013, but problem still occures. Any suggestions? Or maybe how can i deal with it using different id's?
aspx page:
<asp:GridView ID="GridView5" runat="server" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333" Height="430px" OnRowCancelingEdit="GridView5_RowCancelingEdit" OnRowDataBound="GridView5_RowDataBound" OnRowEditing="GridView5_RowEditing" OnRowUpdating="GridView5_RowUpdating" Width="100%" CssClass="gridview" GridLines="none">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField ItemStyle-Width="100">
<EditItemTemplate>
<asp:Button ID="btn_Update_fl" runat="server" CommandName="Update" Text="Ок" />
<asp:Button ID="btn_Cancel_fl" runat="server" CommandName="Cancel" Text="Отмена" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btn_Edit_fl" runat="server" CommandName="Edit" Text="✎" Enabled='<%# Flag %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="08:00 - 17:00" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lbl_first_fl" runat="server" Text='<%# Eval("First") %>' Visible="true"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lbl_first_fl" runat="server" Text='<%# Eval("First") %>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_first_fl" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField/>
</Columns>
</asp:GridView>
OnRowUpdating event:
protected void GridView5_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
DropDownList First_fl = GridView5.Rows[e.RowIndex].FindControl("ddl_first_fl") as DropDownList;
con = new SqlConnection(cs);
con.Open();
//updating the record
SqlCommand cmd_fl = new SqlCommand("Update [Duty].[dbo].[Schedule_FirstLine] set First='" + First_fl.Text + "', con);
cmd_fl.ExecuteNonQuery();
con.Close();
GridView5.EditIndex = -1;
ShowDataFirstLine();
}
Binding Gridview:
protected void ShowDataFirstLine()
{
DateTime date = Convert.ToDateTime(Calendar1.VisibleDate.Date.ToString());
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
string GridDS_FirstLine = "set dateformat dmy Select DutyDate,WeekDay,First, Second from [Duty].[dbo].[Schedule_FirstLine] WHERE DutyDate >= '" + firstDayOfMonth + "' AND DutyDate <= '" + lastDayOfMonth + "'";
dt_FirstLine = new DataTable();
con_FirstLine = new SqlConnection(cs);
con_FirstLine.Open();
adapt_FirstLine = new SqlDataAdapter(GridDS_FirstLine, con_FirstLine);
adapt_FirstLine.Fill(dt_FirstLine);
if (dt_FirstLine.Rows.Count > 0)
{
GridView5.DataSource = dt_FirstLine;
GridView5.DataBind();
}
GridView5.Columns[0].Visible = true;
}
You name the event on the grid like this?
<asp:GridView ID="TaskGridView" runat="server"
AutoGenerateEditButton="True"
AllowPaging="true"
OnRowEditing="TaskGridView_RowEditing"
OnRowCancelingEdit="TaskGridView_RowCancelingEdit"
OnRowUpdating="TaskGridView_RowUpdating"
OnPageIndexChanging="TaskGridView_PageIndexChanging">
</asp:GridView>

Categories

Resources