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
}
}
}
Related
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
}
}
Intro
I'm trying to add a custom row on every 25th row. (25, 50, 75...) The custom row should be like
(start sale button)(create customer
button)(textbox)(textbox)(textbox)(textbox)(textbox)
Essentially mimicking the example gridview's format below. The reason for this is to quickly add a customer and do something with them. Moving forward once the information is inside the textboxes won't be an issue.
Using:
ASP.net
C#
The Problem
I've come across a lot of different examples for doing this, but none where I add a row that's different from the item templates that are already there. In this case having a textbox on the 25th row instead of a label. I'm not sure if this is possible or where to begin with this.
Declaration of the gridview
<asp:GridView ID="grdCustomersSearched" runat="server" AutoGenerateColumns="false" OnRowCommand="grdCustomersSearched_RowCommand" AllowPaging="True" PageSize="25" OnPageIndexChanging="grdCustomersSearched_PageIndexChanging" >
<Columns>
<asp:TemplateField HeaderText="Sale">
<ItemTemplate>
<asp:LinkButton ID="lbtnStartSale" CommandName="StartSale" CommandArgument='<%#Eval("CustomerId") %>' Text="Start Sale" runat="server">Start Sale</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View Profile">
<ItemTemplate>
<asp:LinkButton ID="lbtnViewCustomer" CommandName="ViewProfile" CommandArgument='<%#Eval("CustomerId") %>' Text="View Profile" runat="server">View Profile</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer Number">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("CustomerId") %>' ID="key"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer Name">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("firstName") + " " + Eval("lastName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer Address">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("primaryAddress") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone Number">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("primaryPhoneNumber") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No current customer data, please search for a customer
</EmptyDataTemplate>
</asp:GridView>
Codebehind for populating gridview
The following code gathers the data that is needed and populates the gridview.
protected void btnCustomerSearch_Click(object sender, EventArgs e)
{
//Looks through database and returns a list of customers
//based on the search criteria entered
SweetShopManager ssm = new SweetShopManager();
c = ssm.GetCustomerfromSearch(txtSearch.Text);
//Binds the results to the gridview
grdCustomersSearched.Visible = true;
grdCustomersSearched.DataSource = c;
grdCustomersSearched.DataBind();
}
Example of the gridview
This can be done in the RowCreated event of a GridView. This works best with AutoGenerateColumns set to false.
int rowIndex = 0;
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
//the amount of rows in between the inserted rows
int rowsInBetween = 3;
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow && rowIndex % (rowsInBetween + 1) == 0 && rowIndex > 0)
{
//create a new row
GridViewRow extraRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert);
extraRow.BackColor = Color.Green;
//add one cell with text
TableCell cell1 = new TableCell();
cell1.Text = "ExtraRow";
extraRow.Cells.Add(cell1);
//add another one with a textbox and column spanning
TableCell cell2 = new TableCell();
cell2.ColumnSpan = GridView1.Columns.Count - 1;
TextBox tb1 = new TextBox();
tb1.Text = "Inserted TextBox";
cell2.Controls.Add(tb1);
extraRow.Cells.Add(cell2);
//add the new row to the gridview
GridView1.Controls[0].Controls.AddAt(rowIndex, extraRow);
//extra increment the row count
rowIndex++;
}
rowIndex++;
}
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
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;
}
}
How can I change the value of a textbox whenever a dropdownlist within a gridview has its value changed?
On page load, the textbox shows the selected value, but when I change the selection of the dropdownlist, the textbox value doesn't change.
The code is below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField HeaderText="Entry">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duty">
<ItemTemplate>
<asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind is below.
protected void ddl1_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
Duty dy = new Duty();
dt = dy.getdutyid(Convert.ToInt32(dropcontractid.SelectedValue));
DropDownList ddl = (DropDownList)sender;
ddl.DataSource = dt;
ddl.DataTextField = "dutyid";
ddl.DataValueField = "dutyid";
ddl.DataBind();
TextBox1.Text = ddl.SelectedValue;
}
}
You need to use SelectedIndexChanged handler to show selected value:
Markup:
<asp:DropDownList ID="duty" runat="server" OnLoad="ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged"></asp:DropDownList>
Code-behind:
protected void duty_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
DropDownList duty= (DropDownList) gvr.FindControl("duty");
TextBox1.Text = duty.SelectedItem.Value;
}
I had a similar problem using the DropDownLists in GridView. My solution was to adjust the onLoad for the dropdown so that it wouldn't re-write the DropDownList on every post back. This way if there's something there then it won't re-populate it.
protected void dropDownLoad(object sender, EventArgs e)
{
DropDownList dropDown = sender as DropDownList;
if (dropDown.SelectedValue == null || dropDown.SelectedValue == "")
{
// Your Code to populate table
}
}
You should look into using data binding instead. You can bind the textbox.Text to the selecteditem.value, this will ensure that proper updating takes place
this happens to me once then i code like this... but i didnt use the onLoad attribute, tell me if this works,
<asp:TemplateField HeaderText="duty" SortExpression="duty">
<EditItemTemplate>
<asp:TextBox ID="duty" runat="server" Text='<%# Bind("duty_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblduty" runat="server" Text='<%# Eval("duty_Name") %>' />
<asp:DropDownList ID="ddlduty" runat="server" CssClass="dropdownlist"
OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" Visible = "false"
>
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle Width="5%" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>