Passing gridview values(data) to textbox fields - c#

For my view,
In the page:
1) I have a gridview with the select hyperlink in it. The gridview data is from the SQLDataSource.
2) And, I also have a few textboxes (abt 5) - not in the gridview.
What I would like to do is to use the select hyperlink to select the row that i want to edit. And when i click select, the data in the row should come out to their respective textboxes.
How do I go about doing this?

Grid views have inline record editing support, you can enable this functionality by setting the AutoGenerateEditButton property to true. You must specify the name of a stored procedure or SQL query in the UpdateCommand property, this is used to update data in the underlying data base.
From MSDN:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="true"
autogeneratedeletebutton="true"
autogenerateeditbutton="true"
datakeynames="CustomerID"
runat="server">
</asp:gridview>
<asp:sqldatasource id="CustomersSqlDataSource"
selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
updatecommand="Update Customers SET CompanyName=#CompanyName, Address=#Address, City=#City, PostalCode=#PostalCode, Country=#Country WHERE (CustomerID = #CustomerID)"
deletecommand="Delete from Customers where CustomerID = #CustomerID"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server">
</asp:sqldatasource>
See here for the full example code.

Wireup OnSelectedIndexChanged event:
ASPX:
<asp:GridView id="gvTest" OnSelectedIndexChanged="gvTest_SelectedIndexChanged"
..........></asp:GridView>
<asp:TextBox id="text1" runat="server"/>
Code:
protected void gvTest_SelectedIndexChanged(object sender, EventArgs e)
{
//get currently selected row
var r =gvTest.Rows[gvTest.SelectedIndex];
//THIS WAY YOU CAN GET TEXT FROM ALL COLUMNS
text1.Text = r.Cells[r.Cells.Count - 1].Text;
}

protected void gvofertas_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
gvofertas.SelectedIndex = Convert.ToInt32(e.CommandArgument);
switch (e.CommandName)
{
case "ELIMINAR":
{
//lblSolEliminar.Text = "Usuario: " + Convert.ToString(gvCorreos.DataKeys[gvCorreos.SelectedIndex].Values["etspcpusrn"]);
mpeEliminar.Show();
break;
}
case "EDITAR":
{
Limpiar();
Session["NROOFERTAACTUALIZA"] = Convert.ToString(gvofertas.DataKeys[gvofertas.SelectedIndex].Values["efophcodi"]).Trim();
txtDescripcion.Text = Convert.ToString(gvofertas.DataKeys[gvofertas.SelectedIndex].Values["efophdesc"]).Trim();
StartDate.Text= Convert.ToDateTime(gvofertas.DataKeys[gvofertas.SelectedIndex].Values["efophfini"]).ToShortDateString();
EndDate.Text = Convert.ToDateTime(gvofertas.DataKeys[gvofertas.SelectedIndex].Values["efophffin"]).ToShortDateString();
txtRango1Localidades1Agregar.Text = Convert.ToString(gvofertas.DataKeys[gvofertas.SelectedIndex].Values["efophloci"]).Trim();
txtRango2Localidades1Agregar.Text = Convert.ToString(gvofertas.DataKeys[gvofertas.SelectedIndex].Values["efophlocf"]).Trim();
this.mpeAgregar.Show();
BtnGuardar2.Text = "Actualizar";
txtDescripcion.Focus();
break;
}
}
catch (Exception ex)
{
ucMsje.RegistrarMensajeCliente("dvMsjeError", F.m_strImagenError, ex.Message);
}

Related

SQL Select ID from automatically generated rows with C#

Basically whenever i would press a button on my website it would generate some kind of report with the ID and other information. What am trying to do is change one column of the table with SQL statements. I managed to change it but the code changes the column for all the IDs. What am trying to do is change column according to ID, but am still new to C# and SQL so i'm not sure how to get the automatic generated row. Just to highlight that i'm using a button in a gridview to change the value in the column. Below is what i tried:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string order = Request.QueryString["id"];
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["RCManiaConnectionString"].ConnectionString;
con.Open();
if (e.CommandName == "received")
{
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "UPDATE [Orders] SET Status = 'Received' WHERE [ID] ='" + order + "'";
SqlDataReader data = com.ExecuteReader();
}
}
Using DataKeyNames property of grid view you can pass each record's primary key value, assign the same to the button of the record under CommandArgument. The below code is working code. You can try the same.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="ID" OnRowDataBound="GridView1_RowCommand">
<EmptyDataTemplate>
No Data Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="Update" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="btnUpdate" runat="server" CausesValidation="false" OnClick="btnUpdate_Click" CommandName="Select" ImageUrl="~/Contents/Images/classicPencil.svg" Width="20" Height="20" Text="View" CommandArgument='<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//Using Direct button click event
protected void btnUpdate_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = sender as ImageButton;
int ID = Convert.ToInt32(btn.CommandArgument);
//Your code of update data process
}
//Using grid row command event.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument.ToString());
//Your code of update data process
}

asp.net gridview edit mode index

I have a gridview which is populated via a sql data source with the SELECT command: Select * FROM myTable
When the page is first loaded that displays every record in the table.
The gridview has an Edit button for each row and when the user clicks the row I want to update the gridview to display only that result in the gridview so I change the SELECT command of the sql data source to SELECT * FROM myTable WHERE ID = currentEditRow
That works except for one issue, when editing any other row but the first, the Update and Cancel buttons do not show up on the row. It is like is not in edit mode.
Any idea why that is?
Code:
protected void gvResults_RowEditing(object sender, GridViewEditEventArgs e)
{
gvResults.EditIndex = e.NewEditIndex;
SqlDataSource1.SelectCommand = "SELECT * FROM [myTable] WHERE ID = '" + ID + "'";
}
GridView will bind data again automatically when you set a new command to SqlDataSource1.SelectCommand. This made it returns to start mode (Display read-only data with Edit button in GridView).
Otherwise, you trick it as my sample code below ...
This is my GridView binding data with SqlDataSource1, has DataKey names "code". There are three event handlings to implement: OnRowEditing, OnSelectedIndexChanged and OnRowCancelingEdit.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
DataKeyNames="code"
OnRowEditing="GridView1_RowEditing"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCancelingEdit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="std_room_id" HeaderText="Room ID" SortExpression="std_room_id" />
<asp:BoundField DataField="booking_name" HeaderText="Name" SortExpression="booking_name" />
<asp:BoundField DataField="course_id" HeaderText="Course" SortExpression="course_id" />
<asp:BoundField DataField="course_period" HeaderText="Period" SortExpression="course_period" />
<asp:BoundField DataField="start_date" HeaderText="Start Date" SortExpression="start_date" />
<asp:BoundField DataField="end_date" HeaderText="End Date" SortExpression="end_date" />
<asp:CheckBoxField DataField="approved" HeaderText="Approved" SortExpression="approved" />
<asp:CommandField ShowSelectButton="true" SelectText="Edit"/>
<asp:CommandField ShowEditButton="true" Visible="false"/>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT * FROM [BookingRoom]"></asp:SqlDataSource>
</div>
I have two CommandFields: SelectButton to click when user want open Edit Mode, and the second CommandField for display Update and Cancel buttons.
And this is my code-behide
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.Columns[7].Visible = false;
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string code = GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString();
SqlDataSource1.SelectCommand = "SELECT * FROM [BookingRoom] WHERE code = '" + code + "'";
GridView1.Columns[8].Visible = true;
GridView1.SetEditRow(0);
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.Columns[7].Visible = true;
GridView1.Columns[8].Visible = false;
}
I tricked it by show the SelectButton (display text as "Edit") in GridView with all loaded data in start mode. When user selects the row by clicking the SelectButton, it will start to do the steps in GridView1_SelectedIndexChanged which try to display only the selected row in GridView and set Edit Mode to that row togather with displaying the second CommandField (Update and Cancel buttons).
To set Edit Mode by this line GridView1.SetEditRow(0);, it will do the step in GridView1_RowEditing which try to hide the SelectButton.
Final, you have to handle the cancling Edit Mode as in GridView1_RowCancelingEdit which try to display the SelectButton, and hide the Update and Cancel buttons.
I access those two CommandFields by their column index according to my columns in GridView: column index of Select button is 7 and column index of Update and Cancel buttons is 8
Try to interchange the two line of codes:
protected void gvResults_RowEditing(object sender, GridViewEditEventArgs e)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [myTable] WHERE ID = '" + ID + "'";
gvResults.EditIndex = e.NewEditIndex;
}

using session variable within sql query

i have an application where a user logs in and can edit his/other's data. however, if the user is an admin, he gets a gridview with all user's records which he can edit. if the user is not an admin, he will just get a listview where he can edit his own data.
when a user logs into the page, his userid, which is in itself also stored in the db, is stored as a session variable in Session["ID"]. now i need to populate the listview with the user's data. i thought it would be good to just query the data based on the Session["ID"] parameter. but i am not sure how to do this.
EDIT:
ok i have little code regarding this as i have no idea how to do it but i will post what i have. first is the method where i set the session variable of the userid:
objda = new SqlDataAdapter("[GetIDOfUser]", objcon);
objda.SelectCommand.CommandType = CommandType.StoredProcedure;
objda.SelectCommand.Parameters.Add("#Username", SqlDbType.VarChar).Value = tbUsername.Text;
objda.SelectCommand.Parameters.Add("#UserPassword", SqlDbType.VarChar).Value = tbPassword.Text;
String id = (string)objda.SelectCommand.ExecuteScalar();
Session["ID"] = id;
this is my markup:
<asp:ListView ID="ListView1" Visible="False" runat="server" DataSourceID="SqlDataSource2"></asp:ListView>
this is the code where i enable the listview:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserAuthentication"] == null)
{
Response.Redirect("Login.aspx");
}
if (Session["Benutzerart"].ToString() == Enums.Enumerations.Benutzer.Administrator.ToString())
{
GridView1.Visible = true;
//Set controls for admin
}
if (Session["Benutzerart"].ToString() != Enums.Enumerations.Benutzer.Administrator.ToString())
{
ListView1.Visible = true;
//Set controls for other users
}
}
ok guys i have figured it out:
i just make normal listview as in the code above. only the data source has no selectcommand attribute in the markup. this attribute is set in-code:
if (Session["Benutzerart"].ToString() != Enums.Enumerations.Benutzer.Administrator.ToString())
{
ListView1.Visible = true;
SqlDataSource2.SelectCommand = "SELECT [Titel], [Bezeichnung], [Vorname], [Nachname], [Geburtsdatum], [Geburtsort], [Straße], [Nationalität], [Hausnummer], [PLZ], [Ort], [Land], [Mobil], [UrlaubstageGenommen], [UrlaubstageInsgesamt], [Status], [Benutzerart], [Homepage], [Email], [Festnetz], [Fax], [UrlaubstageRest], [Username], [UserPassword] FROM [Benutzer] WHERE [BenutzerID] = '" + Session["ID"] + "'";
}
markup of datasource:
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ></asp:SqlDataSource>
you are binding listview with SqlDataSource, use sqldatasource SelectParameter
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:yourConnection %>"
SelectCommand="SELECT * FROM yourTable WHERE userid = #userid">
<SelectParameters>
<asp:SessionParameter Name="userid" SessionField="ID" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
To select data from DB you can create sql data source and bind it to ListView:
SqlDataSource ds = new SqlDataSource();
ds.ConnectionString = yourDBconnectionString;
ds.SelectCommand = "SELECT * FROM records_table WHERE user_id=#user_id";
ds.SelectParameters.Add("user_id", Convert.ToInt32(Session["id"]));
ListView1.DataSource = ds;
ListView1.DataBind();
Then to bind records fields to ListView on aspx page use (just an example):
<%# Eval("recort_title") %>

Need to add a hyperlinkfield to a gridview containing data from another column

I have a gridview that gets data from an sqldatasource and as a results gets 3 columns from an SQL query: ID, description and price.
What I want to do is adding another column with an hyperlink in the format of page.aspx?id=x where x is the ID code from the first column. This for each row in the table.
I've been looking all morning for how to do this, all I got is that I have to manage the RowDataBound event and use an hyperlinkfield but couldn't find anything else that explained how they actually work together, even the msdn article is kind of vague on the subject or just doesn't have any relevant help for my specific case as I'm managing the gridview from the code-behind.
Also haven't been able to figure how to access strings from the other columns, since it's what I need to insert in the resulting hyperlink.
Here's what I got so far for the creation of the gridview:
private void FillGrid(string qid)
{
SqlDataSource1.ConnectionString = Connessione.connectionString;
SqlDataSource1.SelectCommand = "SELECT art_tessuto_articolo, art_tessuto_descrizione, lipre_prezzo FROM lipre INNER JOIN listini_tessuti ON lipre.lipre_codice = listini_tessuti.listini_codice INNER JOIN art_tessuti ON lipre.lipre_articolo = art_tessuti.art_tessuto_articolo WHERE lipre_codice = #qid AND lipre_prezzo <> 0";
SqlDataSource1.SelectParameters.Clear();
SqlDataSource1.SelectParameters.Add("qid", qid);
GridView1.AllowPaging = true;
GridView1.PageSize = 500;
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
This should do the job.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlControl = new HyperLink();
hlControl.Text = e.Row.Cells[0].Text;
hlControl.NavigateUrl = "page.aspx?id=" + e.Row.Cells[0].Text;
e.Row.Cells[3].Controls.Add(hlControl);
}
}
Use HyperlinkField
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:HyperlinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="page.aspx?ID={0}" />
</Columns>
</asp:GridView>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" Text="VisibleText" NavigateUrl='<%# Eval(columnname) %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Select row from SQL database depending on selected Index

I am trying to display rows from my database based on the primary key when the select button is clicked.
<asp:Panel ID="pnlView" runat="server">
<p>
<asp:Label ID="lblTitle" runat="server" Text="Label"></asp:Label></p>
<p>
<asp:Label ID="lblBody" runat="server" Text="Label"></asp:Label></p>
</asp:Panel>
<asp:GridView ID="GridView1" runat="server" DataSourceID="sdsDocuments" EnableModelValidation="True"
SelectedIndex="0" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:CommandField ShowSelectButton="True" />
</Columns>
</asp:GridView>
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
lblTitle.Text = GridView1.SelectedRow.ToString();
lblBody.Text = GridView1.SelectedIndex.ToString();
SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["blcDocumentationConnectionString"].ConnectionString);
// Create Command Object
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
try
{
// Open Connection
thisConnection.Open();
// Create INSERT statement with named parms
nonqueryCommand.CommandText = "SELECT DocumentTitle,DocumentBody FROM tblDocument WHERE DocumentID = #DocumentID";
// Add parms to Command parms collection
nonqueryCommand.Parameters.Add("#DocumentID", SqlDbType.Int);
// Execute query statement
nonqueryCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
}
finally
{
// Close Connection
thisConnection.Close();
}
In the GridView1_SelectedIndexChanged event, I can't see that you have set value for your parameter #DocumentID
Replace this nonqueryCommand.Parameters.Add("#DocumentID", SqlDbType.Int);
with this one nonqueryCommand.Parameters.AddWithValue("#DocumentID", GridView1.SelectedValue);
Edit: Following your comment, that you also need to display the text in your label, do like...
GridViewRow row = GridView1.SelectedRow;
lblTitle.Text = row.Cells[TitleCellIndex].Text;
lblBody.Text = row.Cells[BodyCellIndex].Text
You are not passing a value in to your SQL parameter for the documentid. If you have your grid populated correctly, the current row value is inside the EventArgs e variable.

Categories