I have a gridview and output generated is
But I want to remove the Column_Name column and want this type of output
Never change SQL query because in this way the query works according to my logic. And I also want to remove   in every textbox and how can I get all the gridview data by using loop and save in SQL Server database?
ASPX:
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<form id="form" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
onrowdatabound="GridView1_RowDataBound">
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="load" Text="gridview" />
<asp:Button ID="Button2" runat="server" OnClick="show" Text="Button" />
<asp:Button ID="Button3" runat="server" OnClick="save" Text="Save" />
</form>
</asp:Content>
Codebehind:
SqlConnection cnn = new SqlConnection("Data Source=LIFE_WELL;Initial Catalog=db_compiler;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
string query = "USE db_compiler SELECT Column_Name FROM tbl_field WHERE Table_Name='deptt'";
SqlCommand cmd = new SqlCommand(query, cnn);
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
adp.Fill(dt);
Session["num"] = dt.Rows.Count;
for (int i = 0; i < dt.Rows.Count; i++)
{
DataColumn dc = new DataColumn(dt.Rows[i]["Column_Name"].ToString());
dt.Columns.Add(dc);
}
DataRow r = table.NewRow();
GridView1.DataSource = table;
GridView1.DataBind();
cnn.Close();
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
Session["table"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TextBox txt = new TextBox();
txt.Text = e.Row.Cells[i].Text;
e.Row.Cells[i].Text = "";
e.Row.Cells[i].Controls.Add(txt);
}
}
}
Change Your Codebehind code:
protected void Page_Load(object sender, EventArgs e)
{
If(!IsPostBack)
{
string query = "USE db_compiler SELECT Column_Name FROM tbl_field WHERE Table_Name='deptt'";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
adp.Fill(dt);
Session["num"] = dt.Rows.Count;
for (int i = 0; i < dt.Rows.Count; i++)
{
DataColumn dc = new DataColumn(dt.Rows[i]["Name"].ToString());
table.Columns.Add(dc); // Make this Column in 2nd DataTable and bind that to Gridview
}
DataRow r = table.NewRow();
Session["table"] = dt;
table.Rows.Add(r); // Add as many row you want to add with for loop
Gridview1.DataSource = table;
Gridview1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TextBox txt = new TextBox();
e.Row.Cells[i].Controls.Add(txt);
}
}
}
You can try with this modified RowDataBound event handler:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 1; i < e.Row.Cells.Count; i++) // Does not process the first cell
{
TextBox txt = new TextBox();
TableCell cell = e.Row.Cells[i];
txt.Text = cell.Text.Replace(" ", ""); // Removes
cell.Text = "";
cell.Controls.Add(txt);
}
}
e.Row.Cells.RemoveAt(0); // Removes the first cell in the row
}
Related
I have placed MultiView in UpdatePanel and added Views dynamically, each has GridView control. I'm able to display only the View which is set at first time. I have added static button for "Next" & "Back". An error "ActiveViewIndex is being set to '0'. It must be smaller than the current number of View controls '0'. For dynamically added views, make sure they are added before or in Page_PreInit event.Parameter name: value" occurs, when I click any button including these two.
Code-behind:
protected void MultiView1_Load(object sender, EventArgs e)
{
try
{
if (DropDownList4.SelectedIndex > 0)
{
int i = 1;
SqlCommand cmd = new SqlCommand("select DISTINCT(schedule) from tender where project = '" + DropDownList1.SelectedItem.ToString() + "'", agr);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string schedule = dr[0].ToString().Trim();
GridView Gridview1 = new GridView();
Gridview1.ID = "Gridview" + i.ToString();
Gridview1.RowDataBound +=new GridViewRowEventHandler(Gridview1_RowDataBound);
Gridview1.EnableViewState = true;
Gridview1.HeaderStyle.BackColor = System.Drawing.Color.Silver;
Gridview1.HeaderStyle.ForeColor = System.Drawing.Color.White;
Gridview1.HeaderStyle.Font.Bold = true;
Gridview1.ForeColor = System.Drawing.Color.Gray;
Gridview1.AlternatingRowStyle.BackColor = System.Drawing.Color.White;
Gridview1.GridLines = GridLines.None;
Gridview1.RowStyle.BackColor = System.Drawing.ColorTranslator.FromHtml("#EFF3FB");
Gridview1.HorizontalAlign = HorizontalAlign.Center;
Gridview1.Width = 900;
DataTable dt = new DataTable();
dt.Columns.Add("SN", typeof(string));
dt.Columns.Add("SCHEDULE", typeof(string));
dt.Columns.Add("MATERIAL", typeof(string));
dt.Columns.Add("UNIT", typeof(string));
dt.Columns.Add("PREVIOUS BOQ QTY", typeof(string));
dt.Columns.Add("CURRENT QTY", typeof(string));
int j = 1;
SqlCommand cmd1 = new SqlCommand("select material from tender where project = '" + DropDownList1.SelectedItem.ToString() + "' AND schedule = '" + schedule + "' order by schedulesubsn ", agr);
SqlDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
DataRow row = dt.NewRow();
string mat = dr1[0].ToString().Trim();
row["SN"] = j;
row["SCHEDULE"] = schedule;
row["MATERIAL"] = mat;
row["UNIT"] = Calfunc.getunit(mat);
row["PREVIOUS BOQ QTY"] = Calfunc.GetLocationBOQ(DropDownList1.SelectedItem.ToString(), DropDownList2.SelectedItem.ToString(), DropDownList3.SelectedItem.ToString(), DropDownList4.SelectedItem.ToString(), schedule, mat);
dt.Rows.Add(row);
j++;
}
dr1.Dispose();
View view = new View();
view.ID = schedule;
view.Controls.Add(Gridview1);
MultiView1.Views.Add(view);
Gridview1.DataSource = dt;
Gridview1.DataBind();
i++;
}
dr.Dispose();
MultiView1.ActiveViewIndex = i-3;
}
}
catch (Exception ex)
{
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (MultiView1.ActiveViewIndex > 0)
{
MultiView1.ActiveViewIndex = MultiView1.ActiveViewIndex - 1;
}
}
protected void Button4_Click(object sender, EventArgs e)
{
if (MultiView1.Views.Count-1 > MultiView1.ActiveViewIndex)
{
TextBox2.Text = (MultiView1.ActiveViewIndex + 1).ToString();
}
}
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox TextBox101 = new TextBox();
TextBox101.ID = "TextBox_C_QTY";
TextBox101.Width = 70;
TextBox101.Text = (e.Row.DataItem as DataRowView).Row["CURRENT QTY"].ToString();
e.Row.Cells[5].Controls.Add(TextBox101);
}
}
aspx:
<asp:UpdatePanel ID="UpdatePanel4" runat="server">
<ContentTemplate>
<div style="overflow-x:auto;">
<asp:MultiView ID="MultiView1" runat="server" onload="MultiView1_Load">
</asp:MultiView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
I've searched for the solution but didn't find any satisfactory or workable (for me).
this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.
im using asp.net and c#
i need to fill gridview from textbox values,
my code is,
<div>
<table class="style1">
<tr>
<td>
Name
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Address
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
Number
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add" />
</td>
</tr>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</td>
</tr>
</table>
</div>
then my .aspx code is,
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Columns.Add("Number");
//First fill all the date present in the grid
for (int intCnt = 0; intCnt < GridView1.Rows.Count; intCnt ++)
{
if (GridView1.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Name"] = GridView1.Rows[intCnt].Cells[0];
dr["Address"] = GridView1.Rows[intCnt].Cells[1];
dr["Number"] = GridView1.Rows[intCnt].Cells[2];
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Name"] = TextBox1.Text;
dr["Address"] = TextBox2.Text;
dr["Number"] = TextBox3.Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}
but the result is, adding single row with value...
next row value is not adding properly...
problem is,
the second entry of textbox values are stored like "System.Web.UI.WebControls.DataControlFieldCell " is display in each cell of second row...
it should be like
dr["Address"] = GridView1.Rows[intCnt].Cells[1].Text;
that is reason you are not getting value properly.
for (int intCnt = 0; intCnt < GridView1.Rows.Count; intCnt ++)
{
if (GridView1.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Name"] = GridView1.Rows[intCnt].Cells[0].Text;
dr["Address"] = GridView1.Rows[intCnt].Cells[1].Text;
dr["Number"] = GridView1.Rows[intCnt].Cells[2].Text;
dt.Rows.Add(dr);
}
}
Extract grid view rows using for each loop , and use the Text property of each cell to assign to your DataTable again.
Here's your click command:
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Columns.Add("Number");
foreach (GridViewRow gr in GridView1.Rows)
{
//using gridviewrow
if (gr.RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Name"] = gr.Cells[0].Text;
dr["Address"] = gr.Cells[1].Text;
dr["Number"] = gr.Cells[2].Text;
dt.Rows.Add(dr);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
You are assigning object of cells not the values.
Get the Text property of cells.
protected void Button1_Click1(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Columns.Add("Number");
//First fill all the date present in the grid
for (int intCnt = 0; intCnt < GridView1.Rows.Count; intCnt++)
{
if (GridView1.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Name"] = GridView1.Rows[intCnt].Cells[0].Text;
dr["Address"] = GridView1.Rows[intCnt].Cells[1].Text;
dr["Number"] = GridView1.Rows[intCnt].Cells[2].Text;
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Name"] = TextBox1.Text;
dr["Address"] = TextBox2.Text;
dr["Number"] = TextBox3.Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}
The ff are codes in my .cs file
private void BindGridview(int rowcount)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("Code", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Course", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Credit", typeof(String)));
if (ViewState["CurrentData"] != null)
{
for (int i = 0; i < rowcount + 1; i++)
{
dt = (DataTable)ViewState["CurrentData"];
if (dt.Rows.Count > 0)
{
dr = dt.NewRow();
dr[0] = dt.Rows[0][0].ToString();
}
}
dr = dt.NewRow();
dr[0] = this.cboCourseCode.Text;
dr[1] = this.txtCourseName.Text;
dr[2] = this.txtCredit.Text;
dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr[0] = this.cboCourseCode.Text;
dr[1] = this.txtCourseName.Text;
dr[2] = this.txtCredit.Text;
dt.Rows.Add(dr);
}
// If ViewState has a data then use the value as the DataSource
if (ViewState["CurrentData"] != null)
{
GridView1.DataSource = (DataTable)ViewState["CurrentData"];
GridView1.DataBind();
}
else
{
// Bind GridView with the initial data assocaited in the DataTable
GridView1.DataSource = dt;
GridView1.DataBind();
}
// Store the DataTable in ViewState to retain the values
ViewState["CurrentData"] = dt;
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[e.RowIndex].Delete();
ViewState["dt"] = dt;
BindGrid();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Code = e.Row.Cells[0].Text;
foreach (Button button in e.Row.Cells[3].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + Code + "?')){ return false; };";
}
}
}
}
protected void cboCourseCode_SelectedIndexChanged(object sender, EventArgs e)
{
this.Populate_Course_Details();
}
protected void BtnAdd_Click(object sender, EventArgs e)
{
/* DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Code"), new DataColumn("Course"), new DataColumn("Credit") });
dt.Rows.Add(this.cboCourseCode.Text, this.txtCourseName.Text, this.txtCredit.Text);
ViewState["dt"] = dt;
BindGrid();*/
if (ViewState["CurrentData"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentData"];
int count = dt.Rows.Count;
BindGridview(count);
}
else
{
BindGridview(1);
}
}
My aspx file also has this gridview
<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound">
<Columns>
<asp:BoundField DataField="Code" HeaderText="Code" />
<asp:BoundField DataField="Course" HeaderText="Course" />
<asp:BoundField DataField="Credit" HeaderText="Credit" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
When I start to delete, I get this error:
check to determine if the object is null before calling the method
Error Reason
in OnRowDeleting function you are creating datatable and assigning viewstate["dt"],which doesn't have current data. that's why it shows Object is Null
Solution
Try This
First make one of the column as data key.consider i want to make "Code" column as datakey.
datakey will help to find specific row to delete
<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound" DataKeyNames="Code">
After That in .cs code
create a datatable with currentdata
make "Code" column as primary key
find particular code(which you want to delete)using find()
then delete that row using delete() function
Reflect the deletion in viewsate["currentdata"]
then bind to gridview
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
string code = GridView1.DataKeys[e.RowIndex].Value.ToString();
if (ViewState["CurrentData"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentData"];
dt.PrimaryKey = new DataColumn[] { dt.Columns["Code"] };
dt.Rows.Find(code).Delete();
ViewState["CurrentData"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
I have created method to store column value of Questions from Question table into array and now I wanted to display in a label one by one on button click event.
public ArrayList BindDataToArray()
{
ArrayList list = new ArrayList();
DataTable dt = new DataTable();
con = new SqlConnection(str);
cmd = new SqlCommand("select Question from Questions", con);
con.Open();
adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
list.Add(dtrow);
}
return list;
}
Try this....
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
CommandArgument="0" />//dEFINATION OF BUTTON ON ASPX PAGE
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList list = new ArrayList();
list=BindDataToArray();
int I=( Convert.ToInt32(Button1.CommandArgument));
if (I < list.Count)
{
Label1.Text = list[I] as string; //Label in which u want to show message
Button1.CommandArgument = (I + 1).ToString();
}
else
{
Label1.Text = "eND OF LIST";
Button1.Enabled = false;
}
}
public ArrayList BindDataToArray()
{
ArrayList list = new ArrayList();
DataTable dt = new DataTable();
con = new SqlConnection(str);
cmd = new SqlCommand("select Question from Questions", con);
con.Open();
adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
list.Add(dtrow["Question"].ToString());
}
return list;
}
Save the list in to the session
initialize a int with value = 0 and store this also in the session.
when the button is clicked
get the list and int from the session
update the label with the list[index] value where index is the int.
increment the int by one and resave it in the session.
It seems that you are looking for gridview control of asp.net.
Example http://www.dotnetfunda.com/articles/article1594-how-to-populate-gridview-from-code-behind.aspx
// in Aspx Page
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
CommandArgument="1" /><asp:Label
ID="Label1" runat="server" Text="Label"></asp:Label>
//in Aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList list = new ArrayList();
list = BindDataToArray();
int I = (Convert.ToInt32(Button1.CommandArgument.Count()));
//int I = (Convert.ToInt32(Button1.CommandArgument));
if (I < list.Count)
{
Label1.Text = list[I] as string; //Label in which u want to show message
Button1.CommandArgument = (I + 1).ToString();
}
else
{
Label1.Text = "eND OF LIST";
Button1.Enabled = false;
}
}
public ArrayList BindDataToArray()
{
ArrayList list = new ArrayList();
DataTable dt = new DataTable();
//con = new SqlConnection(con);
SqlCommand cmd = new SqlCommand("SELECT SurveyName FROM tblSurveyName", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dtrow in dt.Rows) { list.Add(dtrow["SurveyName"].ToString()); }
return list;
}