Reordering Columns in a Gridview Dynamically - c#

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.

Related

(Gridview)1st record is being deleted from database c#

<asp:GridView ID="GridView1" runat="server" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Add Records">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" OnClick="btnadd_Click" CommandName="insert"
Text="Insert"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete Records">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="True" OnClick="btndelete_Click" CommandName="delete"
Text="delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="id">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%#Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Client Name">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%#Bind("client_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lblemail" runat="server" Text='<%#Bind("email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Google Email">
<ItemTemplate>
<asp:Label ID="lblgemail" runat="server" Text='<%#Bind("google_email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact Number">
<ItemTemplate>
<asp:Label ID="lblcont" runat="server" Text='<%#Bind("contact_number") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="role">
<ItemTemplate>
<asp:Label ID="lblrole" runat="server" Text='<%#Bind("role") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
I have a table with 100 record
This is my Gridview I have two buttons add and delete(on Delete buttonClick particular record should be deleted from database) like, I clicked on record number 35(record number 35 should be deleted) but instead record number 1 is being deleted everytime.
public void delete()
{
foreach (GridViewRow g in GridView1.Rows)
{
Label lblname = (Label)g.FindControl("lblname");
Button btnde = (Button)g.FindControl("btndelete");
//Response.Redirect("cs.aspx");
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + lblname.Text + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
}
}
protected void btndelete_Click(object sender, EventArgs e)
{
delete();
GridView1.Visible = false;
}
This is my CS code.
It's because on delete you are deleting record using foreach loop which is not a good way to do. You could try out this:
public void delete(string Name)
{
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + Name + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
}
And on Delete button click find the particular row and send it to delete Method
protected void btndelete_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
string name = ((Label)gvr.FindControl("lblname")).Text;
delete(name);
GridView1.Visible = false;
}
Note: Also you could write your redirection inside button click event on basis of delete method return.
You can find your Label control position and get their value, then delete from database. It will work fine.
public void delete()
{
foreach (GridViewRow g in GridView1.Rows)
{
if(g.RowType == DataControlRowType.DataRow)
{
Label lblname = (Label)g.FindControl("lblname");
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + lblname.Text + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
break;
}
}
}

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>

Issue with updating rows in a gridview

I have gridview where users can edit and update data in gridview but my issue is when i put some text in the Action field, nothing is updated. I have tried to run debug mode so i can watch what what is happening but i don't see the values i typed in the text box, it shows blank in my variable. Here is my aspx code:
<asp:GridView ID="GridView1" runat="server" Width = "855px" AutoGenerateColumns = "False" Font-Names = "Arial"
OnPageIndexChanging = "OnPaging" onrowediting="EditGridView1"
onrowupdating="UpdateGridView1" onrowcancelingedit="CancelEdit" CellPadding="3"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" >
<Columns>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "ID">
<ItemTemplate>
<asp:Label ID="lblQST_SK" runat="server" Text='<%# Eval("QUEST_SK")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="10px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Action">
<ItemTemplate>
<asp:Label ID="lblAction" runat="server" Text='<%# Eval("ACTION")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAction" runat="server" Text='<%# Eval("ACTION")%>' TextMode="MultiLine" Height="80px"></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White"
HorizontalAlign="Left" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
</asp:GridView>
here is my code behind:
protected void UpdateGridView1(object sender, GridViewUpdateEventArgs e)
{
string QUEST_SK = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblQST_SK")).Text;
string ACTION = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAction")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update mytable set ACTION=#ACTION" +
"where QUEST_SK=#QUEST_SK;" +
"SELECT QUEST_SK, ACTION FROM mytable";
cmd.Parameters.Add("#QUEST_SK", SqlDbType.VarChar).Value = QUEST_SK;
cmd.Parameters.Add("#ACTION", SqlDbType.VarChar).Value = ACTION;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Try to write the function below in Page Load Event :
Page_Load()
{
if(IsPostBack)
{
return`;
}
}

Selecting a Datevalue from GridView Cell and Use it as Parameter to a SQL Query

Hi I am Presently running an ASP.NET application
Now problem is with the Next button in the app, whenever someone clicks it, it returns the data of date range SYSDATE + 18 to SYDATE + 36 . But the way it should work is .. it should take the first date value from the GridView Date Cell and Returns the data for GridViewFirstCellDate+18 to GridViewFirstCellDate+36. My Gridview code is al follows. Eg the date in Image is Tuesday,November 19,2013 , so clicking Next button should retrun from 7/12/2013 and 25/12/2013 's data (DD/MM/YYYY)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
CellPadding="3" EnableModelValidation="True" GridLines="Horizontal"
onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="#F7F7F7" />
<Columns>
<asp:TemplateField HeaderText = "Date">
<ItemTemplate>
<asp:Label ID="Date" Runat="Server"
Text='<%# Eval("DUTY_DATE", "{0:dddd,MMMM dd,yyyy}") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Role">
<ItemTemplate>
<asp:Label ID="Role" Runat="Server"
Text='<%# Eval("DUTY_DESC") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's Name">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("FULLNAME") %>' NavigateUrl='<%# Eval("ROW_PASS", "/sites/HQDO/Pages/OfficerDetails.aspx?_ID={0}") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's HomeNo">
<ItemTemplate>
<asp:Label ID="HomeNo" Runat="Server"
Text='<%# Eval("MOBILE_NO") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's HomeNo">
<ItemTemplate>
<asp:Label ID="HomeNo" Runat="Server"
Text='<%# Eval("OFFICE_TEL") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
</asp:GridView>
and the CodeBehind for next button is below
protected void Button3_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "SELECT CONTACTS.ROWID as ROW_PASS,DUTY_ROTA.DUTY_DATE AS DUTY_DATE,DUTY_ROTA.DUTY_TYPE AS DUTY_TYPE,DUTY_ROTA.DUTY_OFFICER AS DUTY_OFFICER,DUTY_TYPES.DESCRIPTION AS DUTY_DESC,CONTACTS.SNAME AS FULLNAME,CONTACTS.MOBILE AS MOBILE_NO,CONTACTS.OFFICETEL AS OFFICE_TEL FROM DUTY_ROTA,DUTY_TYPES,CONTACTS WHERE DUTY_DATE between SYSDATE+18 and SYSDATE+36 AND DUTY_ROTA.DUTY_TYPE = DUTY_TYPES.DUTY_TYPE AND SNAME IS NOT NULL ORDER BY DUTY_DATE";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
GridView1.DataSource = table;
GridView1.DataBind();
}
I tried to catch the value in below way
LabelDate.Text = GridView1.Rows[0].Cells[0].Text;
And then convert it to Date and use it in my SQL. But the LabelDate.Text is unable to store the data not sure why.
Can you buddies please help How could I Capture GridView First Row First Cells data and Add 18 days to it...also I want to use it in my SQL.
You need to add a handler for GridView.RowDataBound
Here's a quick example:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
LabelDate.Text = e.Row.Cells[0].Text;
}
Try :
LabelDate.Text = Convert.ToDateTime(GridView1.Rows[0].Cells[0].Text).AddDays(18).ToShortDateString();
Or:
LabelDate.Text = DateTime.Parse(GridView1.Rows[0].Cells[0].Text).AddDays(18).ToShortDateString();
Or:
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("fr-FR");
Label1.Text = DateTime.ParseExact(GridView1.Rows[0].Cells[3].Text, "g", provider).AddDays(18).ToShortDateString();

Asp.net GridView RowUpdating returning old values

I am trying to make an editable GridView, and when RowUpdating is called the values I get from the TextBoxes are the old values and not the new ones.
My GridView:
<asp:GridView ID="GVProducts" runat="server" AutoGenerateColumns="False"
CellPadding="4" BackColor="White" BorderColor="#3366CC" BorderStyle="None"
BorderWidth="1px" DataKeyNames="phoneId"
onrowcancelingedit="GVProducts_RowCancelingEdit"
onrowdeleting="GVProducts_RowDeleting"
onrowediting="GVProducts_RowEditing" onrowupdating="GVProducts_RowUpdating"
>
<Columns>
<asp:CommandField ButtonType="Button" EditText="ערוך" HeaderText="עריכה"
InsertText="הוסף" NewText="חדש" SelectText="בחר" ShowEditButton="True"
UpdateText="עדכן" CancelText="בטל" DeleteText="מחק"
InsertVisible="False" CausesValidation="False" />
<asp:CommandField ButtonType="Button" CancelText="בטל" DeleteText="מחק"
EditText="ערוך" InsertText="הוסף" NewText="חדש" SelectText="בחר"
ShowDeleteButton="True" UpdateText="עדכן" HeaderText="מחיקה"
CausesValidation="False" />
<asp:BoundField DataField="phoneId" HeaderText="מספר מכשיר" ReadOnly="True"
SortExpression="phoneId" />
<asp:TemplateField HeaderText="צבע">
<ControlStyle Width="100px" />
<FooterStyle Width="100px" />
<HeaderStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="חברה">
<ItemTemplate>
<asp:Label ID="lblBrand" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="דגם">
<ItemTemplate>
<asp:Label ID="lblModel" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="כמות" SortExpression="amount">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("amount") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("amount") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="כמות מינימלית" SortExpression="minAmount">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("minAmount") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("minAmount") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="price" HeaderText="מחיר" SortExpression="price" />
<asp:TemplateField HeaderText="תמונה">
<ItemTemplate>
<asp:Image ID="img" runat="server"
ImageUrl='<%# DataBinder.Eval(Container.DataItem,"pic","images/{0}") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
My RowEditing (UpdateGVLabel is not related):
protected void GVProducts_RowEditing(object sender, GridViewEditEventArgs e)
{
GVProducts.EditIndex = e.NewEditIndex;
GVProducts.DataSource = products;
UpdateGVlabel();
//products = connection.GetData("Select * From Products", "Products");
if (products.Rows.Count > 0)
{
((TextBox)GVProducts.Rows[e.NewEditIndex].Cells[6].Controls[1]).Text = products.Rows[e.NewEditIndex][4].ToString();
((TextBox)GVProducts.Rows[e.NewEditIndex].Cells[7].Controls[1]).Text = products.Rows[e.NewEditIndex][5].ToString();
}
}
My RowUpdating (UpdateGVLabel is not related):
protected void GVProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool abort = false;
int amount = 0, minAmount = 0;
int id = int.Parse(GVProducts.Rows[e.RowIndex].Cells[2].Text);
try
{
amount = int.Parse(((TextBox)GVProducts.Rows[e.RowIndex].Cells[6].Controls[1]).Text);
minAmount = int.Parse(((TextBox)GVProducts.Rows[e.RowIndex].Cells[7].Controls[1]).Text);
if (amount < minAmount)
{
MessageBox.Show("אין אפשרות להגדיר כמות שקטנה מהכמות המינימלית!");
abort = true;
}
if (minAmount <= 0)
{
MessageBox.Show("כמות מינימלית לא יכולה להיות אפס או פחות!\nאם ברצונך לציין שהחנות לא מוכרת את המכשיר הזה, יש ללחוץ על \"מחק\"");
abort = true;
}
if (amount < 0)
{
MessageBox.Show("כמות לא יכולה להיות שלילית");
abort = true;
}
}
catch (FormatException)
{
MessageBox.Show("כמויות חייבות להיות מספרים!");
abort = true;
}
if (!abort)
{
connection = new Connect(Server.MapPath("App_Data/ado1.mdb"));
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Update Products Set amount=" + amount + ", minAmount=" + minAmount + " Where phoneId=" + id;
products = connection.GetData("Select * From Products", "Products");
connection.ChangeDatabase(cmd); GVProducts.EditIndex = -1;
GVProducts.DataSource = products;
UpdateGVlabel();
MessageBox.Show("המכשיר נערך בהצלחה!");
}
}
Thanks!
Try this
protected void GVProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//your code
if (!abort)
{
connection = new Connect(Server.MapPath("App_Data/ado1.mdb"));
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Update Products Set amount=" + amount + ", minAmount=" + minAmount + " Where phoneId=" + id;
cmd.ExecuteNonQuery();//OR "connection.ChangeDatabase(cmd);" if it updates your database
products = connection.GetData("Select * From Products", "Products");
GVProducts.EditIndex = -1;
GVProducts.DataSource = products;
GVProducts.DataBind();
UpdateGVlabel();
MessageBox.Show("המכשיר נערך בהצלחה!");
}
}
The problem was you were calling connection.ChangeDatabase(cmd); to update your database after fetching data from table like this products = connection.GetData("Select * From Products", "Products"); hence you always got old values from your db and values in your db also got updated too..
Also add this GVProducts.DataBind(); after providing datasource GVProducts.DataSource = products; to bind the grid.
Write The code in the row updating
int i=convert.toint32(e.NewValues["Standard"])
IsPostBack() is the answer. We have to check if the Page is posted back or not. If not, then we will bind the Grid.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
Reference : https://taditdash.wordpress.com/2014/06/30/why-gridview-rowupdating-event-is-not-giving-the-updated-values/

Categories

Resources