Getting textbox.text in gridview auto generated edit control - c#

Hi i am having a problem using the auto generated edit button in my gridview.
i am trying to get the username from the edit text box and insert it to my database like so:
<asp:TemplateField HeaderText="User Name">
<ItemTemplate>
<asp:Label ID="UserNamelbl" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="UserNameEdit" Width="100" Text='<%# Eval("Username") %>' Enabled="true" runat="server"></asp:TextBox></EditItemTemplate>
</asp:TemplateField>
c# method that occurs on the update click.
protected void UsersGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = UsersGridview.Rows[e.RowIndex];
Connect c = new Connect("EdenSiteDB.accdb");
string updatesql = "UPDATE Users Set Username= '" + ((TextBox)row.FindControl("UserNameEdit")).Text + "' , Email= '" + ((TextBox)row.FindControl("EmailEdit")).Text + "' , Admin= " + (((CheckBox)row.FindControl("IsAdminBoxEdit")).Checked).ToString() + " WHERE UserID= " + Session["UserId"].ToString() + ";";
OleDbCommand updatecmm = new OleDbCommand(updatesql);
c.TakeAction(updatecmm);
string usersql = "SELECT * FROM Users;";
dt = c.MakeConnection(usersql, "Users");
UsersGridview.EditIndex = -1;
DataBind();
}
While running this is the updatesql:
updatesql = "UPDATE Users Set Username= 'edmx0' , Email= 'edmx0.et#gmail.com' , Admin= True WHERE UserID= 17;"
these are the previouse values. not the new ones i just entered.
but when i debug it, my sql keeps coming up with the initial username, and not the one i just entered.
I assume it has something to do with my gridview binding at that moment but i don't know how to fix it.
Any help would be appreciated!

can you step through to a breakpoint at the OleDbCommand and post the result of
updatesql
before the update command runs?

Related

Searching between 2 column numbers

I want to validate in my webform i have 1 textbox and i want to search number and if the number i search is between the range of 2 numbers in my 2 column i want to show the data in the row of my table.
select * from SSPRequest where StartingSeries = '" + TxtSearch.Text + "' BETWEEN EndingSeries= '"+TxtSearch2.Text+"'"
Well, drop a grid view, and then say have this code:
protected void cmdSearch_Click(object sender, EventArgs e)
{
string strSQL = "select * from SSPRequest where StartingSeries >= #Start " +
" AND EndingSeries <= #End";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST3))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#Start", SqlDbType.Int).Value = txtSearch.Text;
cmdSQL.Parameters.Add("#End", SqlDbType.Int).Value = txtSearch2.Text;
conn.Open();
GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}
}
}
So whatever the sql matches, the grid will display. Your markup could be say this:
Enter Start Number:
<asp:TextBox ID="txtSearch" runat="server" Style="width:25px;padding-right:25px"></asp:TextBox>
Enter End Number:
<asp:TextBox ID="txtSearch2" runat="server" Style="width:25px;padding-right:25px"></asp:TextBox>
<asp:Button ID="cmdSearch" runat="server" Text="Search" style="padding-left:25px;" CssClass="btn" OnClick="cmdSearch_Click" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
Looking at your sql posted, it seems a bit wonkey, and does not make sense. I would fire up sql studio, and hand code the sql with two range values and get the sql working, THEN AND ONLY THEN would I attempt the above code.
So FIRST get a working sql statement BEFORE YOU WRITE ONE line of code.

How to have two columns with the same field but different values in a GridView

I'm currently doing a project in ASP.NET/C# on where I have a GridView which gets two types of data from two different tables, ID and Initials.
The table itself must be sort of like this:
UNIT 1
ID - INITIALS
And a Column right next to it:
UNIT 2
ID - INITIALS
The IDs are being called from Table 2, while the INITIALS are being called from Table 1. Each ID has it's own INITIALS, but my problem is that, since the INITIALS are being called twice, they repeat themselves on the following and previous Columns, as seen here.
My current code (ASPX):
<asp:GridView ID="GridView1" runat="server" CssClass= "table table-hover table-bordered" AllowPaging="false" PageSize="4" OnPageIndexChanging="OnPaging" OnPageIndexChanged="SearchByTagButton_Click" Style="max-width:75%;" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="UNIDADE" HeaderStyle-ForeColor="#B70700" HeaderStyle-Width="34%">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "unidade")%>
-
<%# DataBinder.Eval(Container.DataItem, "sigUnidade")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UNIDADE APOIADA" HeaderStyle-ForeColor="#B70700" HeaderStyle-Width="34%">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "unidadeApoiada")%>
-
<%# DataBinder.Eval(Container.DataItem, "sigUnidade")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
And C#:
SqlDataAdapter da;
DataSet ds1 = new DataSet();
DataSet ds2 = new DataSet();
SqlConnection conn = new SqlConnection(strConn);
da = new SqlDataAdapter("SELECT ts.unidade, u.sigUnidade FROM T_SECRETARIAS ts INNER JOIN UNIDADES u on u.unidade = ts.unidade WHERE '%" + txtCodigoSearch.Text + "%' IS NULL OR LEN('%" + txtCodigoSearch.Text + "%') = 0 OR (ts.unidade='%" + txtCodigoSearch.Text + "%') OR ts.unidade LIKE '%" + txtCodigoSearch.Text + "%'", conn);
da.Fill(ds1);
da = new SqlDataAdapter("SELECT ts.unidadeApoiada, u.sigUnidade FROM T_SECRETARIAS ts INNER JOIN UNIDADES u on u.unidade = ts.unidadeApoiada WHERE '%" + txtCodigoSearch.Text + "%' IS NULL OR LEN('%" + txtCodigoSearch.Text + "%') = 0 OR (ts.unidadeApoiada='%" + txtCodigoSearch.Text + "%') OR ts.unidadeApoiada LIKE '%" + txtCodigoSearch.Text + "%'", conn);
da.Fill(ds2);
ds1.Merge(ds2);
GridView1.DataSource = ds1;
GridView1.DataBind();
I basically join two DataSets, one for each SQL Query, as I found it the only way to join both queries to get both ID's (they're different, as in they're all a "main ID" in Table 1, but in Table 2 they can also be "sub ID's".
I tried to explain my best, but would like my table to be formatted as ID - INITIALS without any repetitions. If I could get any help, I'd be really appreciated.
Starting from comments, you can have the following code:
SqlDataAdapter da;
DataSet ds1 = new DataSet();
SqlConnection conn = new SqlConnection(strConn);
da = new SqlDataAdapter("SELECT ts.unidade, ts.unidadeApoiada, u1.sigUnidade as sigUnidade1, u2.sigUnidade as sigUnidade2 FROM T_SECRETARIAS ts INNER JOIN UNIDADES u1 on u1.unidade = ts.unidade INNER JOIN UNIDADES u2 on u2.unidade = ts.unidadeApoiada WHERE....", conn);
da.Fill(ds1);
GridView1.DataSource = ds1;
GridView1.DataBind();
and in aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="UNIDADE">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "unidade")%>
-
<%# DataBinder.Eval(Container.DataItem, "sigUnidade1")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UNIDADE APOIADA">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "unidadeApoiada")%>
-
<%# DataBinder.Eval(Container.DataItem, "sigUnidade2")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
How about using just one query with UNION .
So you would have
SELECT ts.unidade , u.sigUnidade FROM T_SECRETARIAS ts INNER JOIN UNIDADES ..
UNION
SELECT ts.unidadeApoiada as unidas, u.sigUnidade FROM T_SECRETARIAS ts INNER JOIN ...
You have to use the same name for the output on both Queries
You just create one column like phone number, it's the perfect example for your question I think. I am also trying to resolve these type of errors. That's why I am telling you use this code. I hope it's useful for you. It's sample code to merge multiple textbox values into a singe cell in gridview.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=RVM\SQLEXPRESS;Initial Catalog=rvm;Persist Security Info=True;User ID=sa;Password=rvmbecse");
string str = "insert into multext values('"+TextBox1.Text +" , " + TextBox2.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(str,con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataBind();
//Response.Write("<script>alert('HI RVM Data inserted Successfully')</script>");
}

Change Dynamically the BoundFields in a GridView

I have a GridView inside a UpdatePanel. In some cases, I have to show different columns in this GridView so I need to change the BoundFields that are specified in my aspx.
How can I change the BoundFields to make the GridView be filled for a different query and different fields ?
ASPX
<cc1:GridView ID="grdImoveis" CssClass="StyleGrid" Width="100%" runat="server" ShowHeader="false"
AutoGenerateColumns="False" DataSourceID="dsGrid" BorderWidth="0px" GridLines="None"
AllowPaging="True" EnableModelValidation="True" >
<AlternatingRowStyle BackColor="White" CssClass="EstiloDalinhaAlternativaGrid" HorizontalAlign="Center" />
<RowStyle CssClass="EstiloDalinhaGrid" HorizontalAlign="Center" />
<Columns>
<asp:BoundField HeaderText="Nome" DataField="NomeCompleto" />
<asp:BoundField HeaderText="Cargo" DataField="DescricaoCargo1" />
<asp:BoundField HeaderText="Data Cadastro" DataField="DataHora" />
<asp:TemplateField ControlStyle-CssClass="acoes_lista_imovel" HeaderText="Curso">
<ItemTemplate>
<div class="acoes_lista_imovel">
<%# montaIcones(Eval("Usuario_Id").ToString())%>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</cc1:GridView>
CODE BEHIND
protected void btnSelecionarData_OnClick(object sender, EventArgs e)
{
string select = string.Empty;
select += "SELECT San_Credenciada.Apelido, San_Usuario.NomeCompleto, San_Usuario.Usuario_Id, San_Usuario.DescricaoCargo1, "
+ "CONVERT(varchar, San_Usuario.DataHora, 103) AS DataHora, San_UsuarioCurso.Cv, San_UsuarioCurso.Institucional, "
+ "San_UsuarioCurso.Copon, San_UsuarioCurso.ManualCaptacaoESistema, San_UsuarioCurso.PosturaProfissional, San_UsuarioCurso.Certificado "
+ "FROM San_Usuario "
+ "JOIN San_Credenciada "
+ "ON San_Usuario.Credenciada_Id = San_Credenciada.Credenciada_Id "
+ "JOIN San_UsuarioCurso "
+ "ON San_Usuario.Usuario_Id = San_UsuarioCurso.Usuario_Id "
+ "WHERE San_Usuario.Provisorio = 1 "
+ "AND San_Usuario.Excluido = 0 "
+ "AND San_UsuarioCurso.DataCurso = '" + this.DtBusca.Value.ToString() +"' "
+ "GROUP BY San_Credenciada.Apelido, San_Usuario.NomeCompleto, San_Usuario.Usuario_Id, "
+ "San_Usuario.DescricaoCargo1, San_Usuario.DataHora, San_UsuarioCurso.Cv, San_UsuarioCurso.Institucional, "
+ "San_UsuarioCurso.Copon, San_UsuarioCurso.ManualCaptacaoESistema, San_UsuarioCurso.PosturaProfissional, San_UsuarioCurso.Certificado "
+ "ORDER BY San_Usuario.DataHora ASC ";
dsGrid.ConnectionString = c.Con;
dsGrid.SelectCommand = select;
dsGrid.Dispose();
If I understand your query correctly, you want to change columns. A simple solution for this is that do not specify fields in your aspx page, just set AutoGenrateColumns = True in your grid view decleratoin
Your grid should look like
<asp:GridView ID="gv" runat="server" AutoGenrateColumns="True" />
// Now in your code behind just specify its DataSource property it will fill up with your desired columns.
// Your query should contain only those columns which you want to show
you can put GridView and Enable "AutoGenerateColumns=True" and for each case that you like fill grid view.
you can use this code for create ImageField Programmatically :
ImageField img = new ImageField();
img.HeaderText = "Pictuer";
img.DataImageUrlField ="Pic";
img.DataImageUrlFormatString = "images\\{0}";
GridView1.AutoGenerateColumns = false;
GridView1.Columns.Add(img);

ListItems text not showing in Listbox

The strangest thing happened to me in my asp.net application with a Listbox -- the ListItems are not showing their text. I know they are there because I can see them when I set breakpoints, and on top of that I am using almost the exact same code as I am on another page where they show up just fine. My listbox is on a panel that is called by a modal pop-up that looks like this:
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
DynamicServicePath="" Enabled="True" TargetControlID="Button5"
BackgroundCssClass="modalBackground"
DropShadow="True"
PopupControlID="Panel2" CancelControlID="Button5" OkControlID="Button5">
</asp:ModalPopupExtender>
<asp:Panel ID = "Panel2" runat="server" CssClass="modalPopup">
<table>
<tr>
<td class="style3">
<asp:Label ID="Label5" runat="server" Text="The following users are queued front of you. Select 'OK' to add your name to the queue and 'Cancel' to cancel."></asp:Label>
</td>
</tr>
</table>
<asp:ListBox ID="ListBox6" runat="server" Width="100%"></asp:ListBox>
<center>
<asp:Button ID="reqOk" runat="server" Text="OK" onclick="reqOk_Clk" />
<asp:Button ID="reqCncl" runat="server" Text="Cancel" onclick="reqCncl_Clk" />
</center>
</asp:Panel>
The listbox (ListBox6) is populated like in the code behind page like this:
SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings
["something"].ConnectionString);
SqlCommand sqlcommand = new SqlCommand();
sqlcommand.Connection = sqlconn;
string cmd = "";
cmd = " SELECT devices.requestQueue, devices.invnumber FROM devices WHERE devices.invnumber='" + str + "'";
sqlcommand.CommandText = cmd;
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
object[] obj = dt.Rows[0].ItemArray;
sqlconn.Close();
hasRequest = true;
int i2 = 0;
if (!obj[0].Equals(System.DBNull.Value))
{
string see = (string)obj[0];
string[] words = see.Split(',');
foreach (string word in words)
{
i2++;
if (word.Contains(getname(HttpContext.Current.User.Identity.Name)))
{
showStuff = false;
ListItem item = new ListItem(word);
ListBox6.Items.Add(item);
ModalPopupExtender1.Show();
Label5.Text = "You have already requested " + (string)ViewState["inventory"] + ". Please press cancel and request a different device.";
reqOk.Visible = false;
}
else
{
ListItem item = new ListItem(word);
ListBox6.Items.Add(item);
}
}
}
/*foreach (object o in ListBox6.Items)
{
Label4.Text += o.ToString() + " ";
}*/
if (showStuff == true)
{
ListBox6.DataBind();
if (obj[0].Equals(System.DBNull.Value) || (string)obj[0] == "")
i2 = 0;
Label5.Text = "The following " + i2 + " user(s) are queued in front of you for device " + str + ". Select 'OK' to add your name to the queue and 'Cancel' to cancel. Your name will not be added to the queue if you select 'Cancel'.";
ModalPopupExtender1.Show();
What makes this super frustrating is that when I uncomment this peice of code from above:
/*foreach (object o in ListBox6.Items)
{
Label4.Text += o.ToString() + " ";
}*/
then Label 4 properly shows each of the items in the ListBox that I want my ListBox to be showing! So, I know the ListItems are being added to the ListBox correctly; I just cannot understand why they are not showing any text in the listbox. Any ideas?? Thanks
From your code, the problem is stemming showStuff being true. You are adding items manually to your ListBox, then calling ListBox.DataBind on a non-databound list box, which will empty it's contents (since AppendDataBoundItems is not set to true). Either set the DataSource, DataValueField, and DataTextField, or stop databinding and your ListBox should function as expected.
Ok, I am going to assume this is just some weird bug that happened. To resolve this I just made a new modal popup extender, a new panel and changed the name on the listbox and the modal popup extender. Now it works just fine... Really weird but it works now.

Changing values inside my GridView on load with ASP.NET

I have a GridView that gets populated with data from a SQL database, very easy.
Now i want to replace values in my one column like so......
If c04_oprogrs value is a 1 then display Take in the GridView.
If c04_oprogrs value is 2 then display Available in the GridView.
What code changes must i make to change to my code to display the new values.
My Grid
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="281px" Width="940px"
Font-Size="X-Small" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="c04_oprogrs" HeaderText="Order Progress"
SortExpression="c04_oprogrs" />
<asp:BoundField DataField="c04_orderno" HeaderText="Order No."
SortExpression="c04_orderno" />
<asp:BoundField DataField="c04_orddate" HeaderText="Date of Order"
SortExpression="c04_orddate" DataFormatString="{0:d/MM/yyyy}" />
<asp:BoundField DataField="c04_ordval" HeaderText="Order Value"
SortExpression="c04_ordval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_delval" HeaderText="Delivered Value"
SortExpression="c04_delval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_invval" HeaderText="Invoice Value"
SortExpression="c04_invval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_orddesc" HeaderText="Order Description"
SortExpression="c04_orddesc" >
<ControlStyle Width="300px" />
</asp:BoundField>
</Columns>
</asp:GridView>
My Page load
SqlConnection myConnection;
DataSet dataSet = new DataSet();
SqlDataAdapter adapter;
//making my connection
myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SAMRASConnectionString"].ConnectionString);
adapter = new SqlDataAdapter("Select TOP 40 c04_credno, c04_orderno, c04_orddate, c04_ordval, c04_delval, c04_invval, c04_oprogrs, c04_orddesc FROM C04ORDS WHERE c04_credno = '" + Session["CreditorNumber"] + "'AND c04_oprogrs <> 9 ORDER BY c04_orddate DESC", myConnection);
adapter.Fill(dataSet, "MyData");
GridView1.DataSource = dataSet;
Session["DataSource"] = dataSet;
GridView1.DataBind();
Etienne
EDIT:
MY FINAL SOLUTION
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Find the value in the c04_oprogrs column. You'll have to use
string value = e.Row.Cells[0].Text;
if (value == "1")
{
e.Row.Cells[0].Text = "Take";
}
else if (value == "2")
{
e.Row.Cells[0].Text = "Available";
}
}
}
You can use the RowDataBound event for this. Using this event you can alter the content of specific columns before the grid is rendered.
To clarify a little. First you add a template column with a label to your grid view (see also the answer by ranomore):
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="myLabel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Next you implement the RowDataBound event (I haven't checked the code below, so it may contain some syntax errors):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Find the value in the c04_oprogrs column. You'll have to use
// some trial and error here to find the right control. The line
// below may provide the desired value but I'm not entirely sure.
string value = e.Row.Cells[0].Text;
// Next find the label in the template field.
Label myLabel = (Label) e.Row.FindControl("myLabel");
if (value == "1")
{
myLabel.Text = "Take";
}
else if (value == "2")
{
myLabel.Text = "Available";
}
}
}
You could use a template column and call a function in your code behind.
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text='<%#FieldDisplay(Eval("c04_oprogrs")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
then in your code behind do
protected string FieldDisplay(int c04_oprogrs)
{
string rtn = "DefaultValue";
if (c04_oprogrs == 1)
{
rtn = "Take";
}
else if (c04_oprogrs == 2)
{
rtn = "Available";
}
return rtn;
}
Without using a function. The ternary statement is in VB. If you have to nest another ternary statement to really test for 2 then it'd be easier to go with rwwilden's solution.
<asp:TemplateField HeaderText="Order Progress" SortExpression="c04_oprogrs" >
<ItemTemplate>
<asp:Label runat="server" ID="Label1" Text='<%# IIF(CInt(Eval("c04_oprogrs")) = 1, "Take", "Available") %>' />
</ItemTemplate>
</asp:TemplateField>
You could add a field in the SQL Statement
adapter = new SqlDataAdapter("Select TOP 40 c04_credno, c04_orderno, c04_orddate,
c04_ordval, c04_delval, c04_invval, c04_oprogrs, c04_orddesc ,
CASE c04_oprogrs WHEN 1 THEN "Take" WHEN 2 THEN "Available" ELSE "DontKnow" END AS
Status FROM C04ORDS WHERE c04_credno = '" + Session["CreditorNumber"] + "'AND
c04_oprogrs 9 ORDER BY c04_orddate DESC", myConnection);
And make that new field part of the BoundColumn in the markup.
Pardon my SQL syntax but I hope you get the idea.
EDIT: Do not use the syntax = '" + Session["CreditorNumber"] + "'.
See sql injection attack and how to avoid it using parameterized SQL.
This is the best efficient way.
Make a case in sql server view, like :-
select case <columnname>
when 1 then 'available'
when 0 then 'not available'
end as <columnname>
from <tablename>

Categories