how to get total of all column if GridView Paging is set as “True”? - asp.net

this code display total of column in each page of grid view footer I want to display total of all columns in all pages footer
if (e.Row.RowType == DataControlRowType.DataRow)
{
string deb = ((Label)e.Row.FindControl("debit")).Text;
string cred = ((Label)e.Row.FindControl("credit")).Text;
decimal totalvalue = Convert.ToDecimal(deb) - Convert.ToDecimal(cred);
amount += totalvalue;
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = amount.ToString();
Label lblDebAmount = (Label)e.Row.FindControl("debit");
Label lblCredamount = (Label)e.Row.FindControl("credit");
float debtotal = (float)Decimal.Parse(lblDebAmount.Text);
float credtotal = (float)Decimal.Parse(lblCredamount.Text);
totalPriced += debtotal;
totalPricec += credtotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label totallblCAmount = (Label)e.Row.FindControl("totallblDebAmount");
Label totallblCredAmount = (Label)e.Row.FindControl("totallblCredAmount");
totallblCAmount.Text = totalPriced.ToString("###,###.000");
totallblCredAmount.Text = totalPricec.ToString("###,###.000");
}
}

Why do it when the row is data bound? Why not do it when you originally bind the data?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DataTable dt = Database.GetData();
GridView1.DataSource = dt;
GridView1.DataBind();
//calculate here by manually adding up the debit/credit column from dt
//or do a separate database call that calculates the sum, ex: select sum(debits), sum(credits) from general_ledger
}
}
It makes sense to let the database do the math calculation for you. You wouldn't need to write your own custom calculation code. Just let the database's sum function handle it.
Here's a little more detail.
//Executes a SqlCommand and returns a DataTable
public class GetDataTable(SqlCommand command)
{
var dt = new DataTable();
using (var connection = new SqlConnection("connectionstring"))
{
command.Connection = connection;
connection.Open();
dt.Load(command.ExecuteReader());
}
return dt;
}
//Executes a SqlCommand and returns a scalar of type T
public static T GetScalar<T>(SqlCommand command)
{
using (var connection = new SqlConnection ("connectionstring"))
{
command.Connection = connection;
connection.Open();
var result = command.ExecuteScalar();
if (result is T)
{
return (T)result;
}
else
{
return (T)Convert.ChangeType(result, typeof(T));
}
}
}
//Load the data into the GridView, then get the credit amount and put the value in a label.
//You'll need to adjust the queries to match your schema
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var tableCommand = new SqlCommand("select columns from table");
GridView1.DataSource = GetDataTable(tableCommand);
GridView1.DataBind();
var creditCommand = new SqlCommand("select sum(stat_amount) from tablename where stat_flag='c'");
var credits = GetScalar<decimal>(creditCommand);
Label1.Text = credits;
}
}

Related

How to add TemplateField to a gridview in the code behind?

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:

How to get modified value of TextBox

This is PageLoad code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//DropDownList Binding through bussiness logic
Bussiness_logic.DropDownList_Bind(DDL_U, "SHORT_DESC", "UNIT_CODE", "UNIT_SOURCE");
Bussiness_logic.DropDownList_Bind(DDL_Branch, "TYPE_DESC", "TYPE_CODE", "BRANCH_SOURCE");
}
if (Request.QueryString["File"] != null)
{
string fileNo = Request.QueryString["File"].ToString();
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("LINK_DATA", Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE", fileNo);
SqlDataReader dtr = com.ExecuteReader();
if (dtr.HasRows)
{
dtr.Read();
{
TxtFile.Text = dtr["FILE_NO"].ToString();
DDL_Branch.SelectedValue = dtr["TYPE_DESC"].ToString();
TxtSub.Text = dtr["SUBJECT"].ToString();
DDL_U.SelectedValue = dtr["SHORT_DESC"].ToString();
}
}
Bussiness_logic.CloseConnection();
Label1.Text = "";
}
}
I have get value of QueryString from another page and file my fields according to File variable fetching data from database corresponding to File data .Fields(Two Textbox and two DropDwnList) are filling correctly but when i modify data in textbox or DDL and Click on Update button then it is not updating data .
Update Button code
protected void BtnUpdate_Click(object sender, EventArgs e)
{
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("UPDATE_DATA",Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE_NO", TxtFile.Text);
com.Parameters.AddWithValue("#SUB",TxtSub.Text);
com.Parameters.AddWithValue("#UNIT",DDL_U.SelectedValue);
com.Parameters.AddWithValue("#BRANCH",DDL_Branch.SelectedValue);
com.ExecuteNonQuery();
Label1.Text = "Action perfomed successfully !!!";
Bussiness_logic.CloseConnection();
Bussiness_logic.Empty_Control(TxtFile, TxtSub, DDL_U, DDL_Branch);
//GridView1.Visible = false;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//DropDownList Binding through bussiness logic
Bussiness_logic.DropDownList_Bind(DDL_U, "SHORT_DESC", "UNIT_CODE", "UNIT_SOURCE");
Bussiness_logic.DropDownList_Bind(DDL_Branch, "TYPE_DESC", "TYPE_CODE", "BRANCH_SOURCE");
if (Request.QueryString["File"] != null)
{
string fileNo = Request.QueryString["File"].ToString();
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("LINK_DATA", Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE", fileNo);
SqlDataReader dtr = com.ExecuteReader();
if (dtr.HasRows)
{
dtr.Read();
{
TxtFile.Text = dtr["FILE_NO"].ToString();
DDL_Branch.SelectedValue = dtr["TYPE_DESC"].ToString();
TxtSub.Text = dtr["SUBJECT"].ToString();
DDL_U.SelectedValue = dtr["SHORT_DESC"].ToString();
}
}
Bussiness_logic.CloseConnection();
Label1.Text = "";
}
}
}
Put Your second if also in first if.Because when you click update button than your page load event fire first.Means your textbox value again set from textbox.So putting your second if inside first if stop setting the textbox value from database on postbask,

How to populate the date present in the database table to Calender asp.net?

My table in the database has the following columns id , eventstart , eventend , eventname
I am trying to bind the event name plus the event start date in the cell of the calender on the date which it is occurring
However i am not able to do so
Following is my code snippet
protected void myCal_DayRender1(object sender, DayRenderEventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter cmd = new SqlDataAdapter("Select * FROM event", con);
cmd.Fill(ds, "Table");
if (!e.Day.IsOtherMonth)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
if ((dr["eventstart"].ToString() != DBNull.Value.ToString()))
{
DateTime dtEvent = (DateTime)dr["eventstart"];
if (dtEvent.Equals(e.Day.Date))
{
Label lbl = new Label();
lbl.BorderColor = System.Drawing.Color.Black;
lbl.BorderStyle = BorderStyle.Double;
lbl.Width = 100;
lbl.Height = 100;
lbl.BackColor = System.Drawing.Color.BlanchedAlmond;
lbl.Text = TextBoxName.Text + "" + TextBoxStart.Text + "" + TextBoxEnd.Text;
e.Cell.Controls.Add(lbl);
}
}
}
}
else
{
}
}
Please help someone
Ok, once again from the start. Now I think I got it. Your problem is probably caused by comparing date with time to date. To get only date without time You can use dt.Date as You can see below. You can consider loading all data on page load because of performance reasons.
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
//get data
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand =
new SqlCommand("select * from event", connection);
adapter.Fill(ds);
}
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
//mark dates in calendar
foreach (DataRow dr in ds.Tables[0].Rows)
{
DateTime dt = (DateTime)dr.Field<DateTime?>("eventstart");
if (e.Day.Date == dt.Date)
{
e.Cell.BackColor = System.Drawing.Color.Yellow;
//add event lable to day
Label lbl = new Label();
lbl.BorderColor = System.Drawing.Color.Black;
lbl.BorderStyle = BorderStyle.Double;
lbl.BackColor = System.Drawing.Color.BlanchedAlmond;
lbl.Text = "Event text";
e.Cell.Controls.Add(lbl);
}
}
}

How to make updatable GridView in ItemTemplate

I want to show Employee details in GridView. My client wants that he should be able to update the record without clicking on Edit button to update. Hence I kept everything in the ItemTemplate field of the GridView.
My Database tables are:
Emp(EmpNo, EName, Sal, DeptNo)
Dept(DeptNo, DeptName, Location)
Hence, I have written one sp to get data: EmpNo, EName, Sal, DeptName
Here, I want to show DeptName field in DropDownList. Here only I am facing the problem. DropDownList is not filling with proper DeptName value, but the first field.
My code-behind is like below:
public partial class GvwEmployee : System.Web.UI.Page
{
SqlConnection objConn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["STERIAConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = EmployeeList;
GridView1.DataBind();
}
}
private List<Employee> EmployeeList
{
get{
List<Employee> employeeList = new List<Employee>();
SqlCommand objCmd = new SqlCommand("usp_GetEmpDetails", objConn);
objCmd.CommandType = CommandType.StoredProcedure;
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
while (objDR.Read())
{
Employee employee = new Employee();
employee.EmpNo = Convert.ToInt32(objDR["EmpNo"]);
employee.EName = Convert.ToString(objDR["EName"]);
employee.Salary = Convert.ToDouble(objDR["Salary"]);
employee.DeptNo = Convert.ToInt32(objDR["DeptNo"]);
employee.DeptName = Convert.ToString(objDR["DeptName"]);
employeeList.Add(employee);
}
objDR.Close();
objConn.Close();
return employeeList;
}
}
private List<Department> DeptList
{
get
{
List<Department> deptList = new List<Department>();
SqlCommand objCmd = new SqlCommand("usp_GetDeptDetails", objConn);
objCmd.CommandType = CommandType.StoredProcedure;
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
while (objDR.Read())
{
Department dept = new Department();
dept.DeptNo = Convert.ToInt32(objDR["DEPTNO"]);
dept.DName = Convert.ToString(objDR["DNAME"]);
dept.Location = Convert.ToString(objDR["Location"]);
deptList.Add(dept);
}
objDR.Close();
objConn.Close();
return deptList;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlDeptName = e.Row.FindControl("ddlDeptName") as DropDownList;
if (ddlDeptName != null)
{
ddlDeptName.DataSource = DeptList;
ddlDeptName.DataBind();
ddlDeptName.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
}
}
}
Can anyone please tell where is the problem, why DeptName DropDownList is not filling with its proper values?
Try this way
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var index = Convert.ToInt32(e.RowIndex.ToString());
GridViewRow row = GridView1.Rows[index];
var ddlDeptName = row.FindControl("ddlDeptName") as ddlDeptName;
if (ddlDeptName != null)
{
ddlDeptName.DataSource = DeptList;
ddlDeptName.DataTextField = "DName";
ddlDeptName.DataValueField = "DeptNo";
ddlDeptName.DataBind();
var item = new ListItem("Select Department", "");
ddlDeptName.Items.Insert(0, item);
}
}
}
I got the solution like below:
In the GridView1_RowDataBound event method, I have written the following line of code to map DropDownList with the Data got from Backend.
//ddlDeptName.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
Now, I have replaced the above line with the following line of code, and hence the problem was solved:
ddlDeptName.SelectedValue = ((Employee)e.Row.DataItem).DeptNo.ToString();
and this has solved my problem.

Bind two datasources into one grid

I have two input controls through which I need to browse and upload the documents.
Below is my ascx
I need to have both teh files uploaded in the gridview.
Below is the code on how I am trying to achieve this.I am creating a datatable for the first upload and then a second datatable for the second upload, and then merging the twodatables into a new combined one and assigning that as the datasource for the gridview.
namespace Sharepoint.WebParts.Upload_WebPart
{
public partial class Upload_WebPartUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
this.btnUpload.Click += new EventHandler(btnUploadUploadClick);
this.uploadsupport.Click+=new EventHandler(uploadsupport_Click);
this.btnSubmit.Click += new EventHandler(btnSubmit_Click);
this.dgdUpload.RowDeleting += new GridViewDeleteEventHandler(dgdUpload_RowDeleting);
}
protected void btnUploadUploadClick(object sender, EventArgs e)
{
fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
string x = Path.GetExtension(fileName);
if (fileName != "")
{
if (x == ".zip")
{
string _fileTime = DateTime.Now.ToFileTime().ToString();
string _fileorgPath = System.IO.Path.GetFullPath(inputFile.PostedFile.FileName);
string _newfilePath = _fileTime + "~" + fileName;
length = (inputFile.PostedFile.InputStream.Length) / 1024;
string tempFolder = Environment.GetEnvironmentVariable("TEMP");
string _filepath = tempFolder + _newfilePath;
inputFile.PostedFile.SaveAs(_filepath);
AddRow(fileName, _filepath, length);
lblMessage.Text = "Successfully Added in List";
}
else
{
lblMessage.Text = "Please upload a zip file";
return;
}
}
else
{
lblMessage.Text = "Select a File";
return;
}
}
private void AddMoreColumns()
{
dt = new DataTable("DT");
dc = new DataColumn("FileName", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("FilePath", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("FileSize", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("KB", Type.GetType("System.String"));
dt.Columns.Add(dc);
Page.Session["DT"] = dt;
}
private void AddRow(string file, string path, double length)
{
dt = (DataTable)Page.Session["DT"];
if (dt == null)
{
AddMoreColumns();
}
dr = dt.NewRow();
dr["FileName"] = file;
dr["FilePath"] = path;
dr["FileSize"] = Convert.ToString(length);
dr["KB"] = "KB";
dt.Rows.Add(dr);
Page.Session["DT"] = dt;
}
Similary i add rows to the datatable dt1.
protected void bindgridview()
{
dt = (DataTable)Page.Session["DT"];
dt1 = (DataTable)Page.Session["DT1"];
joineddt = (DataTable)Page.Session["Files"];
if (joineddt == null)
{
joineddt = dt.Copy();
joineddt.Merge(dt1);
}
this.dgdUpload.DataSource = joineddt;
this.dgdUpload.DataBind();
Page.Session["Files"] = joineddt;
}}
}
Please help me to correct this , also is there a simple way to achieve this.
You can't databind to more than one data source at the same time. If the datatable joineddt does not have SupportName in it then your code would not work.
Rather than trying to try an finagle 2 data sources into one GridView, you should create one data source that has all the data you expect to display in a row of the GridView in one row of the data source.

Resources