Save Grid View Textbox Data to database - c#

I am trying to save grid view text box value and two other text box that are filled by user that are Total Marks and Marks Scored to data base am not sure how to pass back the values of that textboxs to data base on one click of submit
DB where the value to be saved are
Studentname RegNo TotalMarks Marksscored
asdsa 22 125 22
My Gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Names">
<ItemTemplate>
<asp:TextBox ID="txtStudent_Name" runat="server" Text='<%# Eval("StudentFirstName") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Register Number">
<ItemTemplate>
<asp:TextBox ID="txtreg_number" runat="server" Text='<%# Eval("StudentRegID") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Marks">
<ItemTemplate>
<asp:TextBox ID="txttotal_marks" runat="server" Text='' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Marks Scored">
<ItemTemplate>
<asp:TextBox ID="txtmarks_scored" runat="server" Text='' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

protected void Button1_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
DataTable dt = new DataTable();
DataRow row = dt.NewRow();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox txtUsrId=(TextBox)GridView1.Rows[i].FindControl("Your textbox id");
string UserID = txtUsrId.Text;
string q="insert into details (name) values('"+UserID+"')";
SqlCommand cmd = new SqlCommand(q, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
}

Related

Get cell values of textBoxes within ItemTemplate of a Gridview

I have a GridView with textBoxes inside ItemTemplates. I can retrieve the data from the column that was binded to the Gridview on page load, however, I do not see any of the manually entered text when reading the cell values.
The HTML:
<asp:GridView ID="tblRentDue" runat="server" ClientIDMode="Static">
<Columns>
<asp:BoundField DataField="Application_ID" HeaderText="Application ID" HeaderStyle-Wrap="false" />
<asp:BoundField DataField="Month" HeaderText="Month" HeaderStyle-Wrap="false" />
<asp:TemplateField HeaderText="Orignal Amount Due">
<ItemTemplate>
<asp:TextBox ID="txtOrignalAmountDue" runat="server" TextMode="Number" Text='<%# Eval("Original_Amount_Due") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Fees Due">
<ItemTemplate>
<asp:TextBox ID="txtFeesDue" runat="server" TextMode="Number" Text='<%# Eval("Fees_Due") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount Paid">
<ItemTemplate>
<asp:TextBox ID="txtAmountPaid" runat="server" TextMode="Number" Text='<%# Eval("Amount_Paid") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Still Due">
<ItemTemplate>
<asp:TextBox ID="txtTotalStillDue" runat="server" TextMode="Number" Text='<%# Eval("Total_Still_Due") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind:
public DataTable GetDataTable(GridView dtg)
{
DataTable dt = new DataTable();
dt.Columns.Add("Month");
dt.Columns.Add("Original_Amount_Due");
dt.Columns.Add("Fees_Due");
dt.Columns.Add("Amount_Paid");
dt.Columns.Add("Total_Still_Due");
foreach (GridViewRow row in dtg.Rows)
{
DataRow dr;
dr = dt.NewRow();
dr["Month"] = (row.Cells[0].Text); //These values are showing up and was loaded from the database.
dr["Original_Amount_Due"] = (row.Cells[1].Text); //Nothing showing from user input
dr["Fees_Due"] = (row.Cells[2].Text); //Nothing showing from user input
dr["Amount_Paid"] = (row.Cells[3].Text); //Nothing showing from user input
dr["Total_Still_Due"] = (row.Cells[4].Text); //Nothing showing from user input
dt.Rows.Add(dr);
}
return dt;
}
The solution I found - within the foreach loop for each textbox:
TextBox orignalAmount = (TextBox)row.Cells[1].FindControl("txtOrignalAmountDue");
dr["Original_Amount_Due"] = orignalAmount.Text;
There may be a less clunky way of doing this but it does work.

Insert data from gridview to database ,where row value in rows not equal to 0

I want to insert data into sql database from Gridview ,where rows values is not equal to 0 using asp.net C#
Below is my Html and C# code with DataTable and image is attached for more clearification I highlighted in red square where value is not equal to 0, will be inserted into the database.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText=" ID">
<ItemTemplate>
<asp:Label ID="I_ID" runat="server" Text='<%#Bind("I_ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Amount">
<ItemTemplate>
<asp:Label ID="I_Amt" runat="server" Text='<%#Bind("I_Amt")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Cheque_NO">
<ItemTemplate>
<asp:TextBox ID="C_NO" runat="server" ReadOnly="true" Text='<%#Bind("C_NO")%>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Cheque_Amount">
<ItemTemplate>
<asp:TextBox ID="C_Amt" runat="server" ReadOnly="true" Text='<%#Bind("C_Amt")%>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" >
<asp:ListItem Text="Pending" Value="1"></asp:ListItem>
<asp:ListItem Text="Received" Value="2"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C# Data
public partial class cheq : System.Web.UI.Page
{
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new System.Data.DataColumn[4] {
new System.Data.DataColumn("I_ID", typeof(int)),
new System.Data.DataColumn("I_Amt", typeof(int)),
new System.Data.DataColumn("C_NO", typeof(int)),
new System.Data.DataColumn("C_Amt", typeof(int)),
});
dt.Rows.Add(21, 339,500,2);
dt.Rows.Add(22, 622,400,25);
dt.Rows.Add(23, 226,474,23);
dt.Rows.Add(26, 339,0,0);
dt.Rows.Add(27, 339,0,0);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}

Dropdownlist displaying two gridviews

I currently have a drop down list that on selected index changed it displays data in a GridView based of the value of the drop down list. However, it is displaying the data in the existing GridView and then displaying another gridview next to the existing one with the exact information. I am just trying to display the data in the existing open.
C# Code:
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
DataTable table = new DataTable();
using (SqlConnection con = new SqlConnection(#"Data Source=
(local)\;Initial Catalog=SmallBatch;Integrated Security=True;"))
{
con.Open();
SqlDataAdapter DataAdapter = new SqlDataAdapter(string.Format("SELECT Item.ItemID, Item.ItemDesc, Stock_Take_Item.BarQuantity, Stock_Take_Item.StorageQuantity FROM Item INNER JOIN Stock_Take_Item ON Item.ItemID = Stock_Take_Item.ItemID INNER JOIN Stock_Take ON Stock_Take_Item.StockTakeIDNew = Stock_Take.StockTakeIDNew where Stock_Take.Username = '" + DropDownList1.SelectedValue + "'"), con);
DataAdapter.Fill(table);
}
GridView1.DataSource = table;
GridView1.DataBind();
}
}
Existing Gridview:
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="Item ID" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="itemIDAdmin" Text='<%# Eval("ItemID")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="itemDescAdmin" Text='<%# Eval("ItemDesc")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bar Quantity" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="barQuantityAdmin" Text='<%# Eval("BarQuantity")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Storage Quantity" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="storageQuantityAdmin" Text='<%# Eval("StorageQuantity")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Unable to bind multiple dropdownlist in gridview on editing a row

I've two columns Customer Type and File Frequency in the gridview. When the grid is in normal mode I show the values using label. On editing the row, those two columns become dropdowns. I bind the dropdowns using OnRowDataBound="RowDataBound". But, Only first dropdown(whichever first written in the method) in the RowDataBound method getting bind on the edit mode.
.aspx
<asp:GridView ID="gvManageCustomers" DataKeyNames="Ship_To" runat="server" AutoGenerateColumns="False"
OnRowEditing="EditCustomer" OnRowDataBound="RowDataBound" OnRowUpdating="UpdateCustomer"
OnRowCancelingEdit="CancelEdit" CssClass="table table-bordered table-condensed">
<Columns>
<asp:TemplateField HeaderText="Customer Type">
<ItemTemplate>
<asp:Label ID="lblCustType" runat="server" Text='<%# Eval("Customer_Type")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblCustType" runat="server" Text='<%# Eval("Customer_Type")%>' Visible="false">
</asp:Label>
<asp:DropDownList ID="ddlgvCustomerType" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Frequency">
<ItemTemplate>
<asp:Label ID="lblFileFreq" runat="server" Text='<%# Eval("FileFrequency")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblFileFreq" runat="server" Text='<%# Eval("FileFrequency")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddlgvFileFreq" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
.cs
public DataTable FetchCustomerType()
{
string sql = "select distinct Customer_TypeID,Customer_Type from tbl_CustomerType";
SqlDataAdapter da = new SqlDataAdapter(sql, constr);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
public DataTable FetchFileFrequency()
{
string sql = "SELECT distinct FileFrequency_ID,FileFrequency FROM [tbl_FileFrequency]";
SqlDataAdapter da = new SqlDataAdapter(sql, constr);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlgvFileFreq = (DropDownList)e.Row.FindControl("ddlgvFileFreq"); //getting binded
ddlgvFileFreq.DataSource = FetchFileFrequency();
ddlgvFileFreq.DataTextField = "FileFrequency";
ddlgvFileFreq.DataValueField = "FileFrequency_ID";
ddlgvFileFreq.DataBind();
ddlgvFileFreq.Items.FindByValue((e.Row.FindControl("lblFileFreq") as Label).Text).Selected = true;
DropDownList ddlgvCustomerType = (DropDownList)e.Row.FindControl("ddlgvCustomerType");
ddlgvCustomerType.DataSource = FetchCustomerType();
ddlgvCustomerType.DataTextField = "Customer_Type";
ddlgvCustomerType.DataValueField = "Customer_TypeID";
ddlgvCustomerType.DataBind();
ddlgvCustomerType.Items.FindByValue((e.Row.FindControl("lblCustType") as Label).Text).Selected = true;
}
}
}
catch (Exception ex)
{
//log error
errorlog.WriteErrorLog(ex.ToString());
}
}
The problem is in this line, it trows an exeption. That's why only the topmost binding would work.
ddlgvFileFreq.Items.FindByValue((e.Row.FindControl("lblFileFreq") as Label).Text).Selected = true;
But it looks like you want the DropDownList to have the correct SelectedValue. This is how you can do that.
DataRowView row = e.Row.DataItem as DataRowView;
DropDownList ddlgvFileFreq = (DropDownList)e.Row.FindControl("ddlgvFileFreq");
ddlgvFileFreq.DataSource = FetchFileFrequency();
ddlgvFileFreq.DataTextField = "FileFrequency";
ddlgvFileFreq.DataValueField = "FileFrequency_ID";
ddlgvFileFreq.DataBind();
try
{
ddlgvFileFreq.SelectedValue = row["FileFrequency_ID"].ToString();
}
catch
{
}
DropDownList ddlgvCustomerType = (DropDownList)e.Row.FindControl("ddlgvCustomerType");
ddlgvCustomerType.DataSource = FetchCustomerType();
ddlgvCustomerType.DataTextField = "Customer_Type";
ddlgvCustomerType.DataValueField = "Customer_TypeID";
ddlgvCustomerType.DataBind();
try
{
ddlgvCustomerType.SelectedValue = row["Customer_TypeID"].ToString();
}
catch
{
}
<asp:TemplateField HeaderText="Customer Type">
<ItemTemplate>
<asp:Label ID="lblCustType" runat="server" Text='<%# Eval("Customer_Type")%>'></asp:Label>
<asp:Label ID="lblCustTypeID" runat="server" Visible="false" Text='<%# (Eval("Customer_TypeID")) %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlgvCustomerType" runat="server" DataSource="<%# FetchCustomerType() %>" DataValueField="Customer_TypeID" DataTextField="Customer_Type" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Frequency">
<ItemTemplate>
<asp:Label ID="lblFileFreq" runat="server" Text='<%# Eval("FileFrequency")%>'></asp:Label>
<asp:Label ID="lblFileFreqID" runat="server" Visible="false" Text='<%# (Eval("FileFrequency_ID")) %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlgvFileFreq" runat="server" DataSource="<%# FetchFileFrequency() %>" DataValueField="FileFrequency_ID" DataTextField="FileFrequency" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
In onRowEditing Event
((DropDownList)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("ddlgvCustomerType")).SelectedValue = ((Label)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("lblCustTypeID")).Text;
((DropDownList)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("ddlgvFileFreq")).SelectedValue = ((Label)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("lblFileFreqID")).Text;

Why is my data not showing in my GridView? [duplicate]

This question already exists:
how to show data in gridview from arraylist in asp.net?
Closed 8 years ago.
I have a database where there is userid, problemname and status column. I am retrieving this data from database in an ArrayList and returning it. Now to show in GridView I have taken a DataTable and in the DataTable I have put three columns and I just want to show my data that is saved in the ArrayList in these columns by making one row.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
ArrayList myArrayList = ConvertDataSetToArrayList();
// Display each item of ArrayList
DataTable dt = new DataTable();
dt.Columns.Add("User Id");
dt.Columns.Add("Problem Name");
dt.Columns.Add("Status");
foreach (Object row in myArrayList)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["User Id"] = ((DataRow)row)["userid"].ToString();
dt.Rows[dt.Rows.Count - 1]["Problem Name"] = ((DataRow)row) ["problemname"].ToString();
dt.Rows[dt.Rows.Count - 1]["Status"] = ((DataRow)row)["status"].ToString();
}
GridView1.DataSource =dt;
GridView1.DataBind();
}
public ArrayList ConvertDataSetToArrayList()
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT userid,problemname,status FROM problemtable", objsqlconn);
cmd.ExecuteNonQuery();
cmd.CommandType = CommandType.Text;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in myDataSet.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
objsqlconn.Close();
return myArrayList;
}
Here is my html:
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="cdd">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
Why is my data is not showing in my GridView?
You need to bind your data to specific controls in your gridview. For example, you need to have labels in your gridview itemtemplate to bind your data to. Here is an example:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="cdd">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Id">
<ItemTemplate>
<asp:Label ID="lbl_userid" runat="server" Text='<%# Eval("User Id") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Problem Name">
<ItemTemplate>
<asp:Label ID="lbl_problemname" runat="server" Text='<%# Eval("Problem Name") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="status">
<ItemTemplate>
<asp:Label ID="lbl_status" runat="server" Text='<%# Eval("Status") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I agree that an ArrayList is a poor choice, but, regardless of how you're binding the data, you need to tell the gridview what it's supposed to show. You can do this using inline tags or by using an onitemdatabound trigger. I recommend you look up some more examples of gridviews.

Categories