I have a grid view and i need to update it with RowUpdating event, but after updating the new values did not appear, database update with the old values.
here is my code
protected void gvContactInfo_RowEditing(object sender, GridViewEditEventArgs e)
{
gvContactInfo.EditIndex = e.NewEditIndex;
bindingGVContacts(int.Parse(ddlfilterforContact.SelectedValue.ToString()));
}
protected void gvContactInfo_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lbl = ((Label)gvContactInfo.Rows[e.RowIndex].FindControl("lblContactidno"));
DropDownList ddl = ((DropDownList)gvContactInfo.Rows[e.RowIndex].FindControl("ddlInfoType"));
TextBox txtinfo = ((TextBox)gvContactInfo.Rows[e.RowIndex].FindControl("txtValueE"));
TextBox txtext = ((TextBox)gvContactInfo.Rows[e.RowIndex].FindControl("txtExt"));
string queryContactInfo = "update tblContactInfo set ContactInfoType='"+ddl.SelectedItem.Text+"',ContactInfo='"+txtinfo.Text+"',Ext='"+txtext.Text+"' where ContactID=" + int.Parse(lbl.Text.Trim()) + "";
Connection = new SqlConnection(ConnString);
Connection.Open();
SqlCommand cmd = new SqlCommand(queryContactInfo, Connection);
cmd.ExecuteNonQuery();
Connection.Close();
gvContactInfo.EditIndex = -1;
bindingGVContacts(int.Parse(ddlfilterforContact.SelectedValue.ToString()));
}
protected void gvContactInfo_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvContactInfo.EditIndex = -1;
bindingGVContacts(int.Parse(ddlfilterforContact.SelectedValue.ToString()));
}
my databinding code is as follows:
public void bindingGVContacts(int contactID)
{
int contactID1 = contactID;
string queryContactInfo = "SELECT * FROM tblContactInfo where ContactID=" + contactID1 + "";
Connection = new SqlConnection(ConnString);
Connection.Open();
ds = new DataSet();
DataTable dt = new DataTable();
ad = new SqlDataAdapter(queryContactInfo, ConnString);
ad.Fill(ds, "queryContactInfo");
ad.Fill(dt);
Connection.Close();
if (ds.Tables["queryContactInfo"].Rows.Count > 0)
{
gvContactInfo.Columns[0].Visible = true;
gvContactInfo.DataSource = ds.Tables["queryContactInfo"];
gvContactInfo.DataBind();
gvContactInfo.Columns[0].Visible = false;
foreach (GridViewRow grow in gvContactInfo.Rows)
{
Label lbl = ((Label)grow.FindControl("lblContactidno"));
DropDownList ddl = ((DropDownList)grow.FindControl("ddlInfoType"));
DataRow[] dr = dt.Select("ContactNoID=" + lbl.Text.Trim() + "");
if (dr.Length != 0)
{
ddl.SelectedItem.Selected = false;
if (ddl.Items.FindByText(dr[0]["ContactInfoType"].ToString()) != null)
ddl.Items.FindByText(dr[0]["ContactInfoType"].ToString()).Selected = true;
}
}
}
else
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
gvContactInfo.DataSource = dt;
gvContactInfo.DataBind();
gvContactInfo.Rows[0].Visible = false;
}
}
here is my aspx code of gridview:
<asp:GridView runat="server" ID="gvContactInfo" ShowHeader="true" ShowHeaderWhenEmpty="true" Enableviewstate="true"
AutoGenerateColumns="false" ShowFooter="true" OnRowEditing="gvContactInfo_RowEditing" OnRowUpdating="gvContactInfo_RowUpdating" OnRowCancelingEdit="gvContactInfo_RowCancelingEdit" OnRowCommand="gvContactInfo_RowCommand"
CssClass=" CategoriesTable table table-striped table-bordered CategoriesTable1"
onrowdatabound="gvContactInfo_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Value" ItemStyle-Width="5%">
<ItemTemplate>
<asp:Label ID="lblContactidno" runat="server" Text='<%#Eval("ContactNoID")%>' Font-Bold="true"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="INFO Type" ItemStyle-Width="5%">
<ItemTemplate>
<asp:DropDownList ID="ddlInfoType" runat="server">
<asp:ListItem Value="Address" Text="Address"></asp:ListItem>
<asp:ListItem Value="Email-Personal" Text="Email-Personal"></asp:ListItem>
<asp:ListItem Value="Email-Work" Text="Email-Work"></asp:ListItem>
<asp:ListItem Value="Phone-Home" Text="Phone-Home"></asp:ListItem>
<asp:ListItem Value="Phone-Work" Text="Phone-Work"></asp:ListItem>
<asp:ListItem Value="Phone-Mobile" Text="Phone-Mobile"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlInfoType" runat="server">
<asp:ListItem Value="Address" Text="Address"></asp:ListItem>
<asp:ListItem Value="Email-Personal" Text="Email-Personal"></asp:ListItem>
<asp:ListItem Value="Email-Work" Text="Email-Work"></asp:ListItem>
<asp:ListItem Value="Phone-Home" Text="Phone-Home"></asp:ListItem>
<asp:ListItem Value="Phone-Work" Text="Phone-Work"></asp:ListItem>
<asp:ListItem Value="Phone-Mobile" Text="Phone-Mobile"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value" ItemStyle-Width="5%">
<ItemTemplate>
<asp:TextBox ID="txtValue" runat="server" Text='<%#Eval("ContactInfo")%>'></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtValue" runat="server" Text=""></asp:TextBox>
</FooterTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtValueE" runat="server" Text='<%#Eval("ContactInfo")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Extension" ItemStyle-Width="5%">
<ItemTemplate>
<asp:TextBox ID="txtExtension" runat="server" Text='<%#Eval("Ext")%>'></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExtension1" runat="server" Text=""></asp:TextBox>
</FooterTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExt" runat="server" Text='<%#Eval("Ext")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-Width="5%">
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="Edit" CausesValidation="false">Edit</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton runat="server" CommandName="Update" CausesValidation="false">Update</asp:LinkButton>
<asp:LinkButton runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:Button runat="server" Text="ADD" CommandName="Insert"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please provide me a solution.
Just check whether you are getting the new values in gvContactInfo_RowUpdating change event using break points
Set a debugger and check if you are passing the correct (new) value to your sql query string, and use try-catch block to catch any exception when updating.
Also, it is not a good idea to build sql query using string. You should use Parameter to prevent SQL-Injection.
This example shows what could happen with SQL injection.
And this example shows how you can prevent SQL injection in C# using Parameter
Instead of reading the old values directly using the FindControl option like,
Label lbl = ((Label)gvContactInfo.Rows[e.RowIndex].FindControl("lblContactidno"));
you should be using the GridViewUpdateEventArgs.NewValues Property property to get all the new values as key/value pair.
string lblStr = e.NewValues[0].ToString(); //lblContactidno
EDIT
You are reading the existing values of your control using the FindControl method in the Row_Updating event. The problem is that your new values hasn't been updated yet and it's in the process to do so. Hence, it's pulling out the old values. Both old & New values are stored in the event GridViewUpdateEventArgs as key/value pair. So you have to get the new values from there [NewValues property]. The code I have suggested here is to read the value for your label only. check if you're getting the new value for it or not as it's based on the assumption that the label is the first control in the grid.
i got another way to update i.e with the help of RowCommand method
protected void gvContactInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Update"))
{
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
Label lbl = ((Label)gvContactInfo.Rows[RowIndex].FindControl("lblContactidno"));
DropDownList ddl = ((DropDownList)gvContactInfo.Rows[RowIndex].FindControl("ddlInfoType"));
TextBox txtinfo = ((TextBox)gvContactInfo.Rows[RowIndex].FindControl("txtValueE"));
TextBox txtext = ((TextBox)gvContactInfo.Rows[RowIndex].FindControl("txtExt"));
string queryContactInfo = "update tblContactInfo set ContactInfoType='" + ddl.SelectedItem.Text + "',ContactInfo='" + txtinfo.Text + "',Ext='" + txtext.Text + "' where ContactNoID=" + int.Parse(lbl.Text.Trim()) + "";
Connection = new SqlConnection(ConnString);
Connection.Open();
SqlCommand cmd = new SqlCommand(queryContactInfo, Connection);
cmd.ExecuteNonQuery();
Connection.Close();
gvContactInfo.EditIndex = -1;
}
}
Related
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;" />  <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")
I have GridView columns which I'd like to update using RowUpdating event. To do that, I use a dropdownlist in the GridView EditItemTemplate and it works perfectly.
However there's a problem when I enter GridView edit mode; the selected item in dropdownlist is showing its default value, not the previously selected items which is stored in the database. So if a user is editing a different column & overlook the dropdownlist , the GridView column (with the dropdownlist in EditItemTemplate) will be wrongly updated to the dropdownlist default value.
In other words, as I enter GridView edit mode I want the dropdownlist to show (or select) a value binded to my SQL database and not showing its default or first value. I tried using <%# Bind("zone") %>' which works for a textbox but it won't work for dropdownlist. Any idea?
Here's my GridView code:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="ID" AllowSorting="False"
onrowediting="GridView1_RowEditing"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdatabound="GridView1_RowDataBound"
onrowupdating="GridView1_RowUpdating"
EnableViewState="False">
<Columns>
<asp:TemplateField HeaderText="Zone" SortExpression="Zone">
<EditItemTemplate>
<asp:DropDownList ID="ddlZone" runat="server" Width="80px">
<asp:ListItem Value="zone1">Zone 1</asp:ListItem>
<asp:ListItem Value="zone2">Zone 2</asp:ListItem>
<asp:ListItem Value="zone3">Zone 3</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblZone" runat="server" Text='<%# Bind("zone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subzone" SortExpression="Subzone">
<EditItemTemplate>
<asp:TextBox ID="txtSubzone" runat="server" Text='<%# Bind("subzone") %>' Width="100px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblSubzone" runat="server" Text='<%# Bind("subzone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string textZone = (GridView1.Rows[e.RowIndex].FindControl("ddlZone") as DropDownList).SelectedItem.Value;
string textSubzone = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSubzone")).Text;
string query = "UPDATE tblRegion SET zone = '" + textZone
+ "', subzone ='" + Subzone"
+ "' WHERE (ID ='" + entryID + "')";
SqlCommand sqlCmd = new SqlCommand(query, conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
conn.Open();
DataTable dt = new DataTable();
sqlDa.Fill(dt);
conn.Close();
}
Thanks in advance :-)
If your list is always static this should work.
<asp:DropDownList ID="ddlZone" runat="server" Width="80px" SelectedValue='<%# Bind("zone") %>'>
If for some reason it doesn't then you can try setting the selected value from code behind OnDataRowBound event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
var ddl = (DropDownList) e.Row.FindControl("ddlZone");
ddl.SelectedValue = "zone1"; //Your logic to bind the requiered index or value
}
}
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
My requirement is I need to access the Grid view data in a button click event.
I have Grid view with name gvData and have button named Update.
On click of update button I am saving data entered in the grid by user to DB.
Please suggest me in getting this done. Code snippets would be of great help.
I am populating the gridview on page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt;
String SQL = "SELECT * FROM tbl_Class";
string sConstr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr))
{
using (SqlCommand comm = new SqlCommand(SQL, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt = new DataTable();
da.Fill(dt);
}
}
}
gvMarks.DataSource = dt;
gvMarks.DataBind();
}
}
<asp:GridView ID="gvMarks" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name"/>
<asp:TemplateField HeaderText="One">
<ItemTemplate>
<asp:TextBox ID="txt1" runat="server" Text='<%# Bind("One") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Two">
<ItemTemplate>
<asp:TextBox ID="txt2" runat="server" Text='<%# Bind("TWO") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Three">
<ItemTemplate>
<asp:TextBox ID="txtThree" runat="server" Text='<%# Bind("THREE") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Four">
<ItemTemplate>
<asp:TextBox ID="txt4" runat="server" Text='<%# Bind("FOUR") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FIVE">
<ItemTemplate>
<asp:TextBox ID="txtFive" runat="server" Text='<%# Bind("FIVE") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SIX">
<ItemTemplate>
<asp:TextBox ID="txt6" runat="server" Text='<%# Bind("SIX") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnUpdae" runat="server" Text="Update Marks" OnClick="btnUpdae_Click" />
protected void btnUpdae_Click(object sender, EventArgs e)
{
//Need to acces the grid view rows and colums here
}
fetch row one by one by foreach or for loop and save the data.
Click This to know more about save the gridview data to your database
You can go with the following approach-
TextBox txt=(TextBox)gvMarks.Rows[i].Cells[0].FindControl("txt1");
string txtOne= txt.Text;
You can use this with for loop and for all the text boxes. Then insert/update the data taken in string variable like txtOne(above used) into the table.Then bind the grid again. You can hit the following link for another solution.
http://forums.asp.net/t/1647616.aspx?Get%20Value%20of%20TextBox%20inside%20the%20GridView%20in%20c%20
I hope this can make your work done.
Try this.
protected void btnUpdae_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)gvMarks.Rows[rowIndex].Cells[0].FindControl("txt1");
TextBox box2 = (TextBox)gvMarks.Rows[rowIndex].Cells[1].FindControl("txt2");
TextBox box3 = (TextBox)gvMarks.Rows[rowIndex].Cells[2].FindControl("txt3");
TextBox box4 = (TextBox)gvMarks.Rows[rowIndex].Cells[3].FindControl("txt4");
TextBox box5 = (TextBox)gvMarks.Rows[rowIndex].Cells[4].FindControl("txt5");
TextBox box6 = (TextBox)gvMarks.Rows[rowIndex].Cells[5].FindControl("txt6");
//get the values from the TextBoxes
//then add it to the collections with a comma "," as the delimited values
sc.Add(box1.Text + "," + box2.Text + "," + box3.Text+ "," + box4.Text + "," + box5.Text+ "," + box6.Text);
rowIndex++;
}
//Call the method for executing inserts or update
}
}
}
I am not able to pre-populate CheckBoxList3 in my app. I have successfully retrieved string data from database and passed to array but routine fails with:
NullReferenceException:Object not set to instance of an object error at line:
ListItem currentCheckBox = cb3.Items.FindByValue(items[i].ToString());
readMyString() method uses SqlDataReader to read and split a string column from SQL table then pass the values for example: "A, B, C" to string array to identify which of 6 checkboxes should be selected. Code reference: [http://mikesdotnetting.com/Article/53/Saving-a-user's-CheckBoxList-selection-and-re-populating-the-CheckBoxList-from-saved-data]
HTML CODE:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" CellPadding="4" DataKeyNames="MyID"
DataSourceID="sdsmyTable1" ForeColor="#333333" GridLines="None"
onrowdeleted="GridView1_RowDeleted"
onrowdeleting="GridView1_RowDeleting"
onrowupdated="GridView1_RowUpdated"
onrowupdating="GridView1_RowUpdating"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowediting="GridView1_RowEditing"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdatabound="GridView1_RowDataBound">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="myID" HeaderText="myID" ReadOnly="True"
SortExpression="myID" />
<asp:BoundField DataField="Date1" HeaderText="Date driver lic issued"
SortExpression="Date1" />
<asp:TemplateField HeaderText="chooseOne" SortExpression="chooseOne">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("chooseOne") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="RadioButtonList2" runat="server" SelectedValue='<%# Bind("chooseOne") %>' Font-Size="Small"
RepeatDirection="Horizontal">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="MyCommaSeparatedString" SortExpression="MyCommaSeparatedString">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("MyCommaSeparatedString") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("MyCommaSeparatedString") %>'></asp:TextBox>
<asp:CheckBoxList ID="CheckBoxList3" runat="server" Font-Size="Small"
RepeatDirection="Horizontal">
<asp:ListItem Value="A">A</asp:ListItem>
<asp:ListItem Value="B">B</asp:ListItem>
<asp:ListItem Value="C">C</asp:ListItem>
<asp:ListItem Value="D">D</asp:ListItem>
<asp:ListItem Value="E">E</asp:ListItem>
<asp:ListItem Value="F">F</asp:ListItem>
</asp:CheckBoxList>
</EditItemTemplate>
C# Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//// establish a datarow to dig into its minutia
DataRowView drv = e.Row.DataItem as DataRowView;
// if 1: RowType of gridview control is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//if 2: is datarow in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
RadioButtonList rb2 = (RadioButtonList)e.Row.FindControl("RadioButtonList2");
CheckBoxList cb3 = (CheckBoxList)e.Row.FindControl("CheckBoxList3");
//CheckBoxList cb3 = (CheckBoxList)GridView1.Rows[GridView1.EditIndex].FindControl("CheckBoxList3");
CheckBoxList cb4 = (CheckBoxList)e.Row.FindControl("CheckBoxList4");
// Create an instance of SqlConn class
SqlConnClass getMyStr= new SqlConnClass();
//Return datareader to read Endorsements column from database
SqlDataReader rdr = getMyStr.selectMyString(GetMyID());
try
{
// column
if (rb2 != null)
{
rb2.SelectedValue = drv[2].ToString();
}
// column
//CheckBoxList cb3 = (CheckBoxList)e.Row.FindControl("CheckBoxList3");
if (cb3 != null)//if (cb3 contains 6 checkboxes (I, N, H, X, T, K)
{
//bind checkbox manually
cb3.DataSource = sdsDatasource;
cb3.DataTextField = "MyCommaSeparatedString ";
cb3.DataValueField = "MyCommaSeparatedString ";
cb3.DataBind();
// if row exists
if (rdr.HasRows)//(dt.Rows.Count > 0 && dt != null)
{
//start reading
rdr.Read();
//extract comma separated string from datareader into one-dimensional array
string[] items = rdr.GetString(0).Split(',');
//returns the upper bound for the indexes of the first dimension of the Array
for (int i = 0; i <= items.GetUpperBound(0); i++)
{
// currentCheckBox IS WHERE NULL OCCURS:
ListItem currentCheckBox = cb3.Items.FindByValue(items[i].ToString());
if (currentCheckBox != null)
{
currentCheckBox.Selected = true;
}
//cb3.SelectedValue = drv[3].ToString();
//}
}// end of for
//close SqlDataReader
rdr.Close();
}
// column
//CheckBoxList cb4 = (CheckBoxList)e.Row.FindControl("CheckBoxList4");
if (cb4 != null)
{
cb4.SelectedValue = drv[4].ToString();
}
}// end of if
}// end of try
catch (IndexOutOfRangeException ex2)
{
System.Diagnostics.Debug.WriteLine(ex2.Message + "; " + ex2.Source + "; " + ex2.TargetSite);
}//end of catch
}// end of if (rowstate)
} // end of if (rowtype)
}// end of method
What I have tried: calling readMyString() method from GridView1_RowDataBound event and/or from GridView1_RowEditing event.
Since CheckBoxList3 is empty to begin with and seems to not want to be null, I added the line cb3.Items[i].Value = items[i]; but the error just moves to the new line instead. I must be missing something.
Can anyone see where I've errored? I must be putting the code in the wrong methods...?
You are trying to find the control in the GridView. The controls are inside the GridView Rows.
So you need to do something like this:
CheckBoxList cb3 = (CheckBoxList) GridView1.Rows[GridView1.EditIndex].FindControl("CheckBoxList3");
Trim the items[i] like below:
ListItem currentCheckBox = cb3.Items.FindByValue(items[i].Trim());