Creating a list of users that haven't updated their job title in a Gridview. I want the list to have a dropdown filled with all the possible title selections and a button next to the dropdown. Then a person can come in and change the title in the dropdown hit the button and its updated and removed from the list.
I have all of this the way I want it to look but I'm trying to figure out how to pass the SelectedValue of the dropdown box in that row to the code behind OnClick. As you can see below the closest I can get is pass the row number in the CommandArgument. Any suggestions how I can get the SelectedValue of the dropdown of that specific row to the OnClick?
EDIT: Maybe I should be using OnRowCommand instead of OnClick?
Looks like this currently:
John Doe | DropdownList Button
Jane Doe | DropdownList Button
Joe Doe | DropdownList Button
Jeff Doe | DropdownList Button
ASPX
<asp:GridView runat="server" ID="TitleView" OnRowDataBound="TitleView_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Fullname" HeaderText="Fullname" />
<asp:TemplateField>
<ItemTemplate>
<div class="input-append"><asp:DropDownList CssClass="span5" ID="TitleList" runat="server">
</asp:DropDownList>
<asp:Button ID="lbnView" runat="server" Text="Update" CssClass="btn btn-primary" OnClick="btn_Clicked"
CommandArgument='<%# ((GridViewRow)Container).RowIndex %>'></asp:Button></div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
public void bindTitleView()
{
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"SELECT U.First + ' ' + U.Last as Fullname, U.UserID, T.Name FROM Employees U LEFT JOIN Titles T ON U.Title = T.ID WHERE U.Active = '1' AND U.Title = '92' ORDER BY Fullname ASC", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
TitleView.DataSource = myDataSet;
TitleView.DataBind();
}
}
protected void TitleView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("TitleList");
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"SELECT ID, Name FROM Titles ORDER BY Name ASC", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable myDataSet = new DataTable();
adp.Fill(myDataSet);
ddl.DataSource = myDataSet;
ddl.DataTextField = "Name";
ddl.DataValueField = "ID";
ddl.DataBind();
}
}
}
protected void btn_Clicked(object sender, EventArgs e)
{
String rowid = ((Button)sender).CommandArgument;
}
SOLUTION: The answer I approved below worked for me once I added !IsPostBack to the Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindTitleView();
}
You can do like that:
protected void btn_Clicked(object sender, EventArgs e)
{
int line = ((GridViewRow)((Button)sender).Parent.Parent).RowIndex;
DropDownList drp = ((DropDownList)TitleView.Rows[line].FindControl("TitleList"));
//Continue the method
}
In your btn_click write the following code
protected void btn_Clicked(object sender, EventArgs e)
{
Button Sample = sender as Button;
GridViewRow row = Sample.NamingContainer as GridViewRow;
DropDownList drp = row.FindControl("TitleList") as DropDownList;
//Now use drp.SelectedValue
}
}
Let me know if this isnt what you are looking for.
Related
I work on asp.net web forms with c# I need to add checkbox column as last column on gridview
but i don't know how to add it
static string con =
"Data Source=DESKTOP-L558MLK\\AHMEDSALAHSQL;" +
"Initial Catalog=UnionCoop;" +
"User id=sa;" +
"Password=321;";
SqlConnection conn = new SqlConnection(con);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewSearch.DataSource = GetDataForSearch();
GridViewSearch.DataBind();
}
}
public DataTable GetDataForSearch()
{
string response = string.Empty;
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select top 10 datelogged AS EntredDatetime, Doc_type AS OrderType, Printer_name, BranchID AS BranchCode, id from Print_Report";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 50000;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
catch (Exception ex)
{
response = ex.Message;
}
finally
{
cmd.Dispose();
conn.Close();
}
return dt;
}
on aspx page
<asp:GridView ID="GridViewSearch" runat="server">
</asp:GridView>
GridViewSearch.DataSource = GetDataForSearch();
DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "X";
checkColumn.HeaderText = "X";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
GridViewSearch.Columns.Add(checkColumn);
GridViewSearch.DataBind();
I get error on line below
GridViewSearch.Columns.Add(checkColumn);
argument 1 can't convert from system.windows.forms.datagridviewcheckbox to system.web.ui.webcontrol.databoundfield
so how to solve this issue please ?
Seems to me, that if you want say a button, or check box, or dropdown?
why not just add it to the markup.
So, say like this:
<div id="MyGridPick" runat="server" style="display:normal;width:40%">
<asp:Label ID="lblSel" runat="server" Text="" Font-Size="X-Large"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" cssclass="table table-hover" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" ItemStyle-Width="120px" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Then my code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
Now, of course I get VERY tired of typing that connection string stuff over and over. So, I have a "genreal" routine like this:
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And the result of running above:
So, kind of hard to make the case to "add" a check box control, when you can just drop one into the gridview.
Same goes for a button, maybe we want a button to "view" or edit the above row, or some such.
So, once again, just drop in a plain jane button, say like this:
<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="bView" runat="server" Text="View" CssClass="btn"
OnClick="bView_Click" />
</ItemTemplate>
</asp:TemplateField>
And now we have this:
And EVEN better?
Well, since that button (or check box) is a plain jane standard control?
then you can add standard events, like a click event, or whatever you want.
Say this code for the button click (shows how to get current row).
protected void bView_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gRow = btn.NamingContainer as GridViewRow;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
DataTable dtHotel = MyRstP(cmdSQL);
General.FLoader(MyEditArea, dtHotel.Rows[0]);
MyGridPick.Style.Add("display", "none"); // hide grid
MyEditArea.Style.Add("display", "normal"); // show edit div area
}
And we now get/see this:
Edit: Process each checked/selected row.
this:
protected void cmdSelProcess_Click(object sender, EventArgs e)
{
// process all rows in GV with check box
String sPK = "";
List<int> MySelected = new List<int>();
foreach (GridViewRow gRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gRow.FindControl("chkSel");
if (chkSel.Checked)
{
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
// add pk value of row to our list
MySelected.Add(PK);
// Or we could process data based on current gRow
if (sPK != "")
sPK += ",";
sPK += PK.ToString();
Debug.Print(PK.ToString());
}
}
// at this point, we have a nice list of selected in MySelected
// or, maybe process as a data table
SqlCommand cmdSQL =
new SqlCommand($"SELECT * FROM tblHotelsA where ID IN({sPK})");
DataTable rstSelected = MyRstP(cmdSQL);
//
foreach (DataRow dr in rstSelected.Rows)
{
// do whatever
}
}
Datagridviewcheckboxcolumn is a Windows formx object. You are working in web forms. Please see the link below for information on the webforms check box field
CheckBoxField checkColumn = new CheckBoxField();
I'm adding a value database table then i want to show on DropDownList. This code working when page is loading. But when i add new value to db, dropdownlist doesn't update. I called after adding value but doesn't change. When i don't use !IsPostBack, dropdownlist updating but in this case DataValueField doesnt working.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
.............
listStudent.DataSource = dt;
listStudent.DataTextField = "st";
listStudent.DataValueField = "id";
listStudent.DataBind();
}
Well, you are free to put the DataTextField and the DataValue field in the markup.
(but does not matter one bit at all).
So, say we have this markup:
(drop down, and a button to add a new value).
<asp:DropDownList ID="cboHotels" runat="server"
DataValueField="HotelName" DataTextField="HotelName" AutoPostBack="True" Width="174px" >
</asp:DropDownList>
<asp:Button ID="cmdAdd" runat="server" Text="+" style="margin-left:10px"
OnClick="cmdAdd_Click"
OnClientClick="return AddHotel();" />
<asp:TextBox ID="txtHotelName" runat="server" ClientIDMode="Static" style="display:none"></asp:TextBox>
<script>
function AddHotel() {
myhotel = prompt("Enter New Hotel Name")
if (myhotel != null) {
document.getElementById('txtHotelName').value = myhotel
return true
}
else {
return false
}
}
</script>
So, we have that "+" button beside the drop to add a new row to the database.
So, our code to fill the drop down looks like this:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
LoadCombo();
}
public void LoadCombo()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT HotelName from tblHotels ORDER BY HotelName",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
cboHotels.DataSource = cmdSQL.ExecuteReader();
cboHotels.DataBind();
// add a blank (no select row)
cboHotels.Items.Insert(0, new ListItem(""));
}
}
And our code to add a new row looks like this:
protected void cmdAdd_Click(object sender, EventArgs e)
{
// add a new hotel to table
using (SqlCommand cmdSQL =
new SqlCommand("INSERT into tblHotels (HotelName) Values(#Hotel)",
new SqlConnection(Properties.Settings.Default.AccessDB)))
{
cmdSQL.Connection.Open();
cmdSQL.Parameters.Add("#Hotel", SqlDbType.NVarChar).Value = txtHotelName.Text;
cmdSQL.ExecuteNonQuery();
}
LoadCombo(); // re-load combo to show new row
// lets be nice and select the row we just added
cboHotels.ClearSelection();
cboHotels.Items.FindByText(txtHotelName.Text).Selected = true;
}
And we get this:
i need to create a webpage containing a grid view with combo box. condition is:- the combo box value should be inserted on my SQL db and update the db/grid view when i click save button.[i added the image of proposed design of the page]any help with the code is so much appreciated! thank you!
GridView Markup
Below I have a simple GridView ASP.Net GridView control populated from the Customers table of Northwind database. It displays 2 columns Contact Name and City of which city is editable via ASP.Net DropDownList control. The identifier column Customer Id is bind to the DataKeyNames property.
<asp:GridView ID="gvCustomers" DataKeyNames = "CustomerId" runat="server" AutoGenerateColumns = "false" OnRowEditing = "EditCustomer" OnRowDataBound = "RowDataBound" OnRowUpdating = "UpdateCustomer" OnRowCancelingEdit = "CancelEdit">
<Columns>
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name" />
<asp:TemplateField HeaderText = "City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>' Visible = "false"></asp:Label>
<asp:DropDownList ID = "ddlCities" runat = "server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Binding the GridView
Below is the code to Bind the GridView control with data.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
Editing the GridView Row
The below events handle the GridView Row Edit and Cancel Edit Events
C#
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
BindData();
}
i am trying to insert into sql table using gridview header template, under the gridview rowcommand i am trying to find the control and it is not able to retrieve the value.
protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
string NetWeightConnectionStrings = ConfigurationManager.ConnectionStrings["NetWeightConnectionString"].ToString();
string query = "INSERT INTO [Net Weight Tracking] ([Date])VALUES (#Date)";
using (SqlConnection sqlConn = new SqlConnection(NetWeightConnectionStrings))
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
String Date = ((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.ParseExact(((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text, "dd/MM/yyyy", null);
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridV1.DataSource = dt;
GridV1.DataBind();
sqlConn.Close();
}
}
}
any help is much appreciated
You can try the RowDataBound Event to get the header template controls.
protected void GridView1__RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
TextBox txtControl = (TextBox)e.Row.FindControl("TextBox31");
}
}
EDIT 1
From the link shared for the GridView Mark up, TextBox31 is not in the HeaderItemTemplate, it is in EditItemTemplate. That would be the reason, you are not able to find the textbox.
<EditItemTemplate>
<asp:TextBox ID="TextBox31" runat="server" Text='<%# Bind("Field4") %>'></asp:TextBox>
</EditItemTemplate>
I Have Menu Table and product table and MenuId ins the common field
Example
Menu Table
MenuId MenuName
11 Shirts
12 Tshirts
Product Table
ProductId ProductName MenuId ProductImage
1 Levisshirts 11 image
2 white shirt 11 image2
have display image in girdview based on drop down selection but the problem is it display same image for every products my code as follows
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
if (!IsPostBack)
ddlbind();
}
private void BindGridData()
{
SqlCommand command = new SqlCommand("SELECT * from rsa_ProductItemTable where MenuId=" + Dropsearch.SelectedItem.Value, con);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataSet ds = new DataSet();
daimages.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.Attributes.Add("bordercolor", "black");
}
public void ddlbind()
{
SqlCommand command = new SqlCommand("SELECT * from rsa_mastermenu", con);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
Dropsearch.DataSource = dt;
Dropsearch.DataTextField = "MenuName";
Dropsearch.DataValueField = "MenuId";
Dropsearch.DataBind();
Dropsearch.Items.Insert(0, new ListItem("Select", "0"));
}
protected void Dropsearch_SelectedIndexChanged(object sender, EventArgs e)
{
int imgid = int.Parse(Dropsearch.SelectedItem.Value);
BindGridData();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image img = (Image)e.Row.FindControl("Image1");
img.ImageUrl = "GridviewImage.ashx?ImID=" + Dropsearch.SelectedItem.Value;
}
}
What am i doing wrong please help me with this
Set image url in aspx ,
something like this
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "your_path" + "ProductImage" %>'
Height="300px" Width="300px"/>
</ItemTemplate>
Plese make sure your_path is physical path where image is stored, for example "~/images/myimg" and your image name is valid, for example image.jpg or image1.png
by this method you can show image in gridview.