I am using ASP.net GridView. There are check boxes that filters the results after selecting the checkbox and clicking a search button but I want to remove the button to filter automatically after selecting the check boxes.
The contents display in the gridview are from a database table
ASP
<b><label style="font-size:25px">Brand</label></b>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="SBrand" DataValueField="SBrand">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT DISTINCT [SBrand] FROM [Stock]"></asp:SqlDataSource>
C#
protected void gvStock_SelectedIndexChanged(object sender, EventArgs e)
{
string id = gvStock.SelectedRow.Cells[0].Text;
Response.Redirect("Details.aspx?ID=" + id);
}
protected void Button1_Click(object sender, EventArgs e)
{
string chkbox = "";
Label1.Visible = false;
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
if (chkbox == "")
{
chkbox = "'" + CheckBoxList1.Items[i].Text + "'";
}
else
{
chkbox += "," + "'" + CheckBoxList1.Items[i].Text + "'";
}
Label1.Text = chkbox;
string mainconn = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "SELECT [pCode],[pID],[bCode], [SBrand], [SDescription], [sCost] , [sPrice] , [SType] , [sSupplierName] , [sSupplierDirect] FROM Stock where SBrand in (" + Label1.Text + ")";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
this.gvStock.DataSource = dt;
this.gvStock.DataBind();
}
}
}
ASPX
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="SBrand" DataValueField="SBrand" AutoPostBack="True" OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
.CS
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
string chkbox = "";
Label1.Visible = false;
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
if (chkbox == "")
{
chkbox = "'" + CheckBoxList1.Items[i].Text + "'";
}
else
{
chkbox += "," + "'" + CheckBoxList1.Items[i].Text + "'";
}
Label1.Text = chkbox;
string mainconn = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "SELECT [pCode],[pID],[bCode], [SBrand], [SDescription], [sCost] , [sPrice] , [SType] , [sSupplierName] , [sSupplierDirect] FROM Stock where SBrand in (" + Label1.Text + ")";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
this.gvStock.DataSource = dt;
this.gvStock.DataBind();
}
}
}
Related
I want when user enters the emp id automatically (on basis of that particular id filled by user)all other information of that particular employee should be filled in the form and should be kept disabled until the emp presses the edit button.
I have designed a registration form in which I have following text boxes and 3 buttons
emp Id
nationality
religion
gender
save button edit button clear button
I have already implemented the coding for save button and clear button. When user clicks on save button after filling the form the data gets stored in the database table
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
SqlCommand cmd = new SqlCommand();
SqlConnection con= new SqlConnection();
SqlConnection conn = new SqlConnection();
SqlDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = #"Data Source=SAKSHIKAUL-LT\SQLEXORESS1;Initial Catalog=registrationForm;Integrated Security=True";
conn.ConnectionString = #"Data Source=SAKSHIKAUL-LT\SQLEXORESS1;Initial Catalog=registrationForm;Integrated Security=True";
con.Open();
conn.Open();
{
string FetchData = "Select * from EmpDetails where EmpId=''";
cmd = new SqlCommand(FetchData, conn);
dr = cmd.ExecuteReader();
if (!this.IsPostBack)
Label1.Text = "";
}
if (dr.Read())
{
TextBox1.Text += dr[0].ToString() + " ";
TextBox2.Text += dr[1].ToString() + " ";
TextBox3.Text += dr[2].ToString() + " ";
TextBox4.Text += dr[3].ToString() + " ";
TextBox5.Text += dr[4].ToString() + " ";
TextBox6.Text += dr[5].ToString() + " ";
TextBox7.Text += dr[6].ToString() + " ";
conn.Close();
{
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{ SqlCommand cmd = new SqlCommand("insert into RegistrationTable" + "(EmpId,Nationality,Religion,Gender,Address,EmailId,Hobbies,MaritalStatus) values (#EmpId,#Nationality,#Religion,#Gender,#Address,#EmailId,#Hobbies,#MaritalStatus)", con);
//string insertQuery = "insert into RegistrationTable(EmpId,Nationality,Religion,Gender,Address,EmailId,Hobbies,Maritalstatus)values (#EmpId,#Nationality,#Religion,#Gender,#Address,#EmailId,#MHobbies,#Maritalstatus)";
cmd.Parameters.AddWithValue("#EmpId", TextBox1.Text);
cmd.Parameters.AddWithValue("#Nationality", TextBox2.Text);
cmd.Parameters.AddWithValue("#Religion", TextBox3.Text);
cmd.Parameters.AddWithValue("#Gender", TextBox4.Text);
cmd.Parameters.AddWithValue("#Address", TextBox5.Text);
cmd.Parameters.AddWithValue("#EmailId", TextBox6.Text);
cmd.Parameters.AddWithValue("#Hobbies", TextBox7.Text);
cmd.Parameters.AddWithValue("#Maritalstatus", TextBox8.Text);
cmd.ExecuteNonQuery();
Label1.Text = "Registered Successfuly";
}
protected void Button2_Click(object sender, EventArgs e)
{ cmd.CommandText = "update RegistrationTable set Nationality =' " + TextBox2.Text + "' where EmpId='" + TextBox1.Text + "' ";
cmd.CommandText = "update RegistrationTable set Religion =' " + TextBox3.Text + "' where EmpId='" + TextBox1.Text + "' ";
cmd.CommandText = "update RegistrationTable set Gender =' " + TextBox4.Text + "' where EmpId='" + TextBox1.Text + "' ";
cmd.CommandText = "update RegistrationTable set Address =' " + TextBox5.Text + "' where EmpId='" + TextBox1.Text + "' ";
cmd.CommandText = "update RegistrationTable set EmailId =' " + TextBox6.Text + "' where EmpId='" + TextBox1.Text + "' ";
cmd.CommandText = "update RegistrationTable set Hobbies =' " + TextBox7.Text + "' where EmpId='" + TextBox1.Text + "' ";
cmd.CommandText = "update RegistrationTable set MaritalStatus =' " + TextBox8.Text + "' where EmpId='" + TextBox1.Text + "' ";
cmd.Connection = con;
cmd.ExecuteNonQuery();
Label1.Text = "Updated Successfuly";
}
protected void Button3_Click(object sender, EventArgs e)
{
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox6.Text = "";
TextBox7.Text = "";
TextBox8.Text = "";
Label1.Text = "Clear All";
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void TextBox1_TextChanged1(object sender, EventArgs e)
{
}
}
Expected output-When user enters the EmpId all other text boxes present in the form should be filled automatically(from already existing database) and should be kept disabled until user clicks on edit button
actual result- user enters the emp id and he has to then fill all the text boxes. Its not getting updated automatically.when user clicks on save button the data get registered in a table and clear button is also clearing all ext boxes.
I am trying to check whilist registrating. When an enterd email exists and then try to register it untill the registration is successfull but I don't want that.
protected void btnRegister_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand ("Select count(*) from tblUsers where Email = '" + txtEmail.Text + "' ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
p.UserName = txtUsername.Text;
p.Email = txtEmail.Text;
p.DOB = Convert.ToDateTime(txtDob.Text);
p.Password = txtPass.Text;
p.InsertUser(p);
Response.Write("Registration Successfull..");
}
else {
Response.Write("This Email is Already Exist...!!");
}
}
else
{
Response.Write("Fail...");
}
}
I have a DropDownList which has a list of tables. Under it there is GridView. Based on the table selected from the drop down list box, I will populate the GridView dynamically. Since the tables could have different column names, I need to create the template field for the GridView dynamically.
Following is my bind method. I have two problems:
I couldn’t wrap the binding part in if (!IsPostBack) since the GridView is populated based on the selection of the DropDownList, so everytime I change the selection, the columns will be duplicated.
And I don’t have any data, I think I need to set ItemTemplate of the tField (TemplateField), but how do I do that?
My bind method
private void BindGridView()
{
DataSet ds = new DataSet();
try
{
ds = …
if (ds.Tables.Count > 0)
{
foreach (DataColumn dc in ds.Tables[0].Columns)
{
TemplateField tField = new TemplateField();
tField.HeaderText = dc.ColumnName;
GridView2.Columns.Add(tField);
}
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
}
else
{
…
}
}
catch (Exception ex)
{
…
}
}
There are various steps that should be taken care of:
STEP I::
Create a class inheriting the ITemplate interface. Override the method InstantiateIn() of the ITemplate interface.
STEP II:
Define a constructor for your class that takes a ListItemType object as its parameter.
STEP III::
If the Control being added to the container's ControlCollection has to be bound to some DataSource Column, then register the
handler for the OnDataBinding event. When the event occurs, retrieve the text from the data source and assign it to your control. For Example, hyprLnk_DataBinding event is defined for Binding Data to your controls created inside ItemTemplate.
public class TemplateGenerator : ITemplate // Class inheriting ITemplate
{
ListItemType type;
string columnName;
public TemplateGenerator(ListItemType t, string cN)
{
type = t;
columnName= cN;
}
// Override InstantiateIn() method
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (type)
{
case ListItemType.Item:
HyperLink hyprLnk = new HyperLink();
hyprLnk.Target = "_blank"; //Optional.
hyprLnk.DataBinding+=new EventHandler(hyprLnk_DataBinding);
container.Controls.Add(hyprLnk);
break;
}
}
// The DataBinding event of your controls
void hyprLnk_DataBinding(object sender, EventArgs e)
{
HyperLink hyprlnk = (HyperLink)sender;
GridViewRow container = (GridViewRow)hyprlnk.NamingContainer;
object bindValue = DataBinder.Eval(container.DataItem,columnName);
// Adding check in case Column allows null values
if (bindValue != DBNull.Value)
{
hyprlnk.Text = bindValue.ToString();
hyprlnk.NavigateUrl = "http://www.google.com";
}
}
}
That's all. Above was just a sample to create ItemTemplate dynamically for GridView and add controls to the Item Template.
Now, Below is the function that will actually carry out the calls to create Template Columns dynamically. You can call this function when required for e.g. from your DropDownList event Handler.
protected void GenerateGridViewColumnsDynamically()
{
// Create the TemplateField
TemplateField firstName = new TemplateField();
firstName.HeaderText = "First_Name";
firstName.ItemTemplate = new TemplateGenerator(ListItemType.Item, "FirstName");
// Showing boundField example just for more context
BoundField lastName = new BoundField();
lastName.DataField = "LastName";
lastName.HeaderText = "Last_Name";
// Add the Columns now
MyGridView.Columns.Add(firstName);
MyGridView.Columns.Add(lastName);
}
NOTE:: FirstName and LastName are the Columns whose Names are passed to the constructor of your custom class: TemplateGenerator.
I have done the same functionality as below with custom paging(using storedProc) for 100+ million records in many tables, update, delete and insert also:
CREATE PROCEDURE [dbo].[sp_Mk]
#PageIndex INT,
#PageSize INT,
#tableName nvarchar(255),
#totalRow INT Output
AS
BEGIN
DECLARE #sql NVARCHAR(MAX)
Declare #anotherSql NVARCHAR(1000)
DECLARE #ParamDefinition NVARCHAR(500)
--DECLARE #totalRow INT
Set #sql = 'WITH TempResult AS( SELECT * FROM '+#tableName+'), TempCount AS ( SELECT COUNT(*) AS MaxRows FROM TempResult )
SELECT * FROM TempResult, TempCount ORDER BY (Select Null)
OFFSET '+CONVERT(VARCHAR(20),(#PageIndex-1)*#PageSize) +' ROWS FETCH NEXT '+CONVERT(VARCHAR(20),#PageSize)+' ROWS ONLY'
PRINT #SQL
EXECUTE sp_executesql #SQL
Set #anotherSql=N'SELECT COUNT(*) as totalRow FROM '+#tableName
SET #ParamDefinition = N'#totalRowOutPut INT OUTPUT'
--PRINT #anotherSql
Execute sp_executesql #anotherSql,
#ParamDefinition,
--#tableNameInput=#tableName,
#totalRowOutPut=#totalRow OUTPUT
End
<asp:GridView CssClass="table-striped header-fixed" ID="grdDynamic" runat="server" AutoGenerateColumns="True" ShowHeaderWhenEmpty="true" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
OnRowEditing="OnRowEditing_grdDynamic" OnRowUpdating="OnRowUpdating_grdDynamic" OnRowCancelingEdit="OnRowCancelingEdit_grdDynamic" OnRowDeleting="OnRowDeleting_grdDynamic" OnRowDataBound="OnRowDataBound_grdDynamic">
</asp:GridView><br/>
<asp:linkbutton id="AddButton" runat="server" commandname="Add" text="Insert: " OnClick="AddNewButton_Click" /><br/>
<asp:Repeater ID="rptPager" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lnkPage" CssClass="pagination-ys" runat="server" Text = '<%#Eval("Text") %>' CommandArgument = '<%# Eval("Value") %>' Enabled = '<%# Eval("Enabled") %>' OnClick = "Page_Changed"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater><asp:HiddenField runat="server" id="hdnPageIndex" Value="1"></asp:HiddenField>
SqlConnectionStringBuilder builder;
int pageSize = 100;
protected void Page_Load(object sender, EventArgs e)
{
builder = new SqlConnectionStringBuilder(connectionString);
if (!IsPostBack)
{
using (SqlConnection connObj = new SqlConnection(connectionString))
{
connObj.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='" + builder.InitialCatalog + "' AND TABLE_NAME Not In('AspNetUsers') Order By TABLE_NAME", connObj))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
ddlTableNames.DataSource = ds;
ddlTableNames.DataBind();
ddlTableNames.Items.Insert(0, new ListItem("Select Table", String.Empty));
}
}
}
//}
//else if(ddlTableNames.Visible) ddlTableNames.Visible = false;
}
protected void ddlTableNames_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlTableNames.SelectedValue != "")
{
grdDynamic.Visible = true;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
else if (grdDynamic.Visible == true) grdDynamic.Visible = false;
}
private void BindGrid(string selectedTable, int pageIndex, bool addNewRow=false)
{
using (SqlConnection connObj = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("sp_Mk", connObj))
{
int recordCount=0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PageIndex", pageIndex);
cmd.Parameters.AddWithValue("#PageSize", pageSize);
cmd.Parameters.AddWithValue("#tableName", ddlTableNames.SelectedValue);
SqlParameter totalRow = new SqlParameter("#totalRow", SqlDbType.Int, 4);
totalRow.Direction = ParameterDirection.Output;
cmd.Parameters.Add(totalRow);
connObj.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
grdDynamic.DataSource = ds.Tables[0];
if (addNewRow) ds.Tables[0].Rows.Add();
recordCount = Convert.ToInt32(ds.Tables[1].Rows[0].ItemArray[0]);
grdDynamic.DataBind();
connObj.Close();
if (totalRow.Value != DBNull.Value)
{
}
this.PopulatePager(recordCount, pageIndex);
}
}
}
private void PopulatePager(int recordCount, int currentPage)
{
double dblPageCount = (double)((decimal)recordCount / pageSize);
int pageCount = (int)Math.Ceiling(dblPageCount);
List<ListItem> pages = new List<ListItem>();
if (pageCount > 0)
{
pages.Add(new ListItem("First", "1", currentPage > 1));
for (int i = 1; i <= pageCount; i++)
{
ListItem item=new ListItem(i.ToString(), i.ToString(), i != currentPage);
if (i == currentPage) item.Attributes.Add("style", "color:red;");
pages.Add(item);
}
pages.Add(new ListItem("Last", pageCount.ToString(), currentPage < pageCount));
}
rptPager.DataSource = pages;
rptPager.DataBind();
}
protected void Page_Changed(object sender, EventArgs e)
{
int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
hdnPageIndex.Value = pageIndex.ToString();
this.BindGrid(ddlTableNames.SelectedValue, pageIndex);
}
protected void OnRowEditing_grdDynamic(object sender, GridViewEditEventArgs e)
{
grdDynamic.EditIndex = e.NewEditIndex;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void OnRowUpdating_grdDynamic(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = grdDynamic.Rows[e.RowIndex];
string updateStatement = string.Empty;
for (int x = 0; x < row.Cells.Count; x++) updateStatement = updateStatement + grdDynamic.DataKeys[e.RowIndex].Values[x] + " = " + grdDynamic.DataKeys[e.RowIndex].Values[x] + ", ";
//int recordId = Convert.ToInt32(grdDynamic.DataKeys[e.RowIndex].Values[0]);
using (SqlConnection con = new SqlConnection(connectionString))
{
//using (SqlCommand cmd = new SqlCommand("UPDATE "+selectedTable"+ SET Name = #Name, Country = #Country WHERE CustomerId = #CustomerId"))
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
grdDynamic.EditIndex = -1;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void OnRowCancelingEdit_grdDynamic(object sender, EventArgs e)
{
grdDynamic.EditIndex = -1;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void OnRowDeleting_grdDynamic(object sender, GridViewDeleteEventArgs e)
{
int recordId = Convert.ToInt32(grdDynamic.DataKeys[e.RowIndex].Values[0]);
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM " + ddlTableNames.SelectedValue + " WHERE RecordId = #recordId"))
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void btnGo_Click(object sender, EventArgs e)
{ int myInt;
if(txtPageSize.Text!=null && txtPageSize.Text !=string.Empty)
if(int.TryParse(txtPageSize.Text, out myInt)) pageSize = myInt;
hdnPageIndex.Value = "1";
this.BindGrid(ddlTableNames.SelectedValue, 1);
}
protected void AddNewButton_Click(object sender, EventArgs e)
{
hdnPageIndex.Value="1";
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value), true);
}
protected void OnRowDataBound_grdDynamic(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != grdDynamic.EditIndex)
{
(e.Row.Cells[0].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
}
}
Hope it helps:
I am getting this error on a row command in my gridview. Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = University.GetConnectionString();
con.Open();
string query = "select [CourseCode], [CourseNumber], [CourseName], [CRN], [Level], [Credit] from CourseTable where Term='" + MyGlobals.currentTerm + " " + MyGlobals.currentYear + "'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
gCourses.DataSource = tab;
gCourses.DataBind();
}
}
protected void gCourses_RowCommand(object sender, GridViewCommandEventArgs e)
{
// *** Retreive the DataGridRow
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
GridViewRow gdrow = gCourses.Rows[row];
DataRow dr = ((DataTable)this.gCourses.DataSource).Rows[gdrow.DataItemIndex];
string crn = dr["CRN"].ToString();
}
.
DataRow dr = ((DataTable)this.gCourses.DataSource).Rows[gdrow.DataItemIndex];
line throws the exception.
What is wrong here? Thanks
Remove the
if (!isPostback)
from your page load
protected void GridView2_OnCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Reply")
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=myconnectionstring; Integrated Security = true; Connect Timeout = 30; User Instance = True";
con.Open();
string div = "','";
GridViewRow selectedRow = GridView2.Rows[Convert.ToInt32(e.CommandArgument)];
SqlCommand cmd = new SqlCommand("INSERT INTO SellerResponse VALUES ('" +
//THIS LINE IS THE ISSUE
Request.QueryString["ID"] + div + selectedRow.Cells[2].Text + div + DateTime.Now.ToString() + div + selectedRow.Cells[3].Text + ((System.Web.UI.WebControls.TextBox)(FindControl(selectedRow.Cells[1].UniqueID))).Text /*this is the cell that contains the textbox*/+ "');", con);
}
}
Any ideas how to implement this?
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Reply")
{
on = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=myconnectionstring; Integrated Security = true; Connect Timeout = 30; User Instance = True";
con.Open();
string div = "','";
GridViewRow selectedRow = GridView2.Rows[Convert.ToInt32(e.CommandArgument)];
SqlCommand cmd = new SqlCommand("INSERT INTO SellerResponse VALUES ('" +
//THIS LINE IS THE ISSUE
Request.QueryString["ID"] + div + GridView2.Rows[index].Cells[2].Text + div + DateTime.Now.ToString() + div + GridView2.Rows[index].Cells[3].Text + ((System.Web.UI.WebControls.TextBox)(GridView2.Rows[index]Cells[1].FindControl("the name of the text box")).Text /*this is the cell that contains the textbox*/+ "');", con);
}
}
catch (Exception ee)
{
string message = ee.Message;
}
}
Note:1- in aspx :CommandArgument='<%#((GridViewRow)Container).RowIndex%>'
2- use RowCommand event for the grid view.